[{"content":"","date":"12 January 2026","externalUrl":null,"permalink":"/articles/","section":"Articles","summary":"","title":"Articles","type":"articles"},{"content":"","date":"12 January 2026","externalUrl":null,"permalink":"/","section":"Bryan Avery","summary":"","title":"Bryan Avery","type":"page"},{"content":"","date":"12 January 2026","externalUrl":null,"permalink":"/categories/c%23/","section":"Categories","summary":"","title":"C#","type":"categories"},{"content":"","date":"12 January 2026","externalUrl":null,"permalink":"/categories/","section":"Categories","summary":"","title":"Categories","type":"categories"},{"content":"Cloud computing is now so normal that most organisations barely think twice about where their data lives. It sits in “the cloud”, it works, it’s secure, and everyone moves on. Yet behind the scenes, a quieter but increasingly important conversation is taking place in boardrooms, regulator meetings and procurement discussions. That conversation is about sovereignty.\nSovereign cloud is one of those terms that sounds technical but is actually very human. At its heart, it asks a simple question: who ultimately controls your data? Not just where the servers are physically located, but whose laws apply, who can access the systems, and whether a foreign government could legally demand that information be handed over.\nMany organisations assume that if their data is stored in UK data centres, the problem is solved. In reality, that only covers data residency. Sovereignty goes further. It looks at legal control, operational control and jurisdiction. If your cloud provider is headquartered overseas, then overseas laws may still apply, even if the data never leaves the UK.\nThis is no longer a niche concern. A decade ago, cloud conversations were about cost savings, convenience and basic security. Today, the landscape feels different. Regulatory scrutiny is higher. Public trust is more fragile. Geopolitical tensions are real. Supply chains are under the microscope. And legislation such as the US CLOUD Act has sharpened awareness that governments can compel their domestic companies to provide access to data, even when that data is held abroad. That does not mean intelligence agencies are casually browsing corporate systems, but it does mean that legal exposure exists, and for some sectors that matters.\nFor most organisations using mainstream cloud services in the UK, the current position is broadly reassuring. If you are running workloads in Azure UK South or UK West, or in AWS’s London region, your data is physically stored in the UK and you are meeting UK GDPR requirements. These platforms are highly secure and widely trusted. For the majority of businesses, this is entirely appropriate and proportionate.\nThe distinction appears when you look at more sensitive environments such as healthcare, central government, defence, policing, or heavily regulated industries. These sectors are increasingly expected to demonstrate not just that their data is secure, but that they understand who governs it and under which legal framework. It becomes an assurance question rather than a purely technical one.\nThis is where the difference between the big cloud providers begins to show. Microsoft has spent years building dedicated environments for public sector use. Azure UK Government provides separate cloud environments designed specifically for UK public sector workloads, with tighter controls around access, operations and governance. These platforms are already in real-world use across government departments, local authorities and parts of the NHS. Alongside this, Microsoft has introduced a wide range of sovereignty controls into its mainstream cloud, including advanced customer-controlled encryption, strong data boundary commitments and deep transparency over administrative access. The effect is that organisations can evidence control, not just assume it.\nAWS, by contrast, has historically focused on delivering a single, highly secure global platform. Its UK regions are robust, compliant and technically excellent, but there is currently no UK-specific sovereign environment equivalent to Azure UK Government. AWS does operate GovCloud, but that platform is built exclusively for US government workloads and is not available for UK use. Recognising the growing demand for sovereignty, AWS has announced a European Sovereign Cloud, designed to operate under a separate European legal entity with European staff and governance, explicitly addressing concerns about foreign legal reach. It is an important move and a clear signal of where the market is going, but it is still in development rather than mainstream reality.\nThe risk itself is often misunderstood. This is not about suggesting that cloud providers are unsafe or untrustworthy. For most organisations, the chance of foreign government access to their data is extremely low. The more realistic risk lies in accountability. Regulators, auditors and clients are increasingly asking tougher questions. They want organisations to demonstrate that they understand their data flows, their legal exposure and their governance model. Simply saying “it’s in the cloud” is no longer enough in some sectors.\nThe direction of travel is clear. Governments want greater national control over sensitive data. Regulators want stronger assurance. Customers want transparency. Cloud providers are responding by creating sovereign offerings, embedding more governance controls and, in some cases, structurally separating their sovereign platforms from their global ones. What feels like an emerging topic today will likely become standard language in architecture documents and procurement frameworks within a few years.\nFor now, the practical picture is straightforward. Azure UK and AWS UK are both secure, compliant and suitable for most use cases. Neither represents full legal sovereignty in the strictest sense. Microsoft currently offers more mature options for UK public sector and regulated environments. AWS is investing heavily to close that gap. Understanding this distinction does not mean organisations need to panic, but it does mean they can have more informed conversations, make better decisions and answer the harder questions with confidence when they inevitably arise.\nAzure vs AWS – Sovereignty Comparison (UK perspective) Area Microsoft Azure Amazon Web Services (AWS) UK data centres Yes (UK South, UK West) Yes (London region) Data residency (UK GDPR) Yes Yes US parent company Yes Yes Subject to US legal reach (e.g. CLOUD Act) Theoretically yes Theoretically yes Fully sovereign by default No No Suitable for most commercial use Yes Yes Summary: both platforms are compliant and safe for most organisations, but neither is fully sovereign in standard form.\nPublic Sector and Higher-Assurance Environments Area Azure UK Government AWS GovCloud Available to UK organisations Yes No (US only) Designed for UK government use Yes No Separate cloud environment Yes Yes Access restricted to national personnel Yes (UK personnel) Yes (US personnel only) Used by government / defence Yes (UK) Yes (US only) Practical UK sovereignty Yes Not applicable Summary: Azure currently offers a real UK sovereign-grade environment. AWS does not yet.\nSovereignty Controls and Governance Features Capability Azure AWS Customer-managed encryption keys Yes Yes Double Key Encryption (extra legal control) Yes No equivalent Strong data boundary commitments (UK/EU) Yes Limited Customer control over support access Strong controls More limited Native tooling for compliance evidence Strong Moderate Easier to defend in UK audits Yes More challenging Summary: Azure provides more built-in features for proving governance and sovereignty.\nFuture Direction Area Azure AWS Sovereign strategy Already active (UK Gov + controls) European Sovereign Cloud announced Separate legal entity for sovereign cloud Partial (controls-based model) Yes (planned EU entity) Market maturity Live and in use Still being built Direction of travel Embedding sovereignty into core cloud Structurally separating sovereign cloud Summary: Microsoft is ahead today. AWS is investing heavily to catch up.\nPlain-English takeaway table Question Answer Are Azure UK and AWS UK safe and compliant? Yes Are they fully sovereign by default? No Does Azure offer a UK sovereign option today? Yes (Azure UK Government) Does AWS offer a UK sovereign option today? No Is AWS building one? Yes (European Sovereign Cloud) Will sovereignty matter more in future? Almost certainly ","date":"12 January 2026","externalUrl":null,"permalink":"/who-really-controls-your-data-the-truth-about-sovereign-cloud/","section":"Articles","summary":"Cloud computing is now so normal that most organisations barely think twice about where their data lives. It sits in “the cloud”, it works, it’s secure, and everyone moves on. Yet behind the scenes, a quieter but increasingly important conversation is taking place in boardrooms, regulator meetings and procurement discussions. That conversation is about sovereignty.\n","title":"Who Really Controls Your Data? The Truth About Sovereign Cloud","type":"articles"},{"content":"","date":"16 December 2025","externalUrl":null,"permalink":"/categories/ai/","section":"Categories","summary":"","title":"Ai","type":"categories"},{"content":"The Ancient Warning “Come, let us build ourselves a city, with a tower that reaches to the heavens… so that we may make a name for ourselves.”\n— Genesis 11:4\nIn the biblical story of the Tower of Babel, humanity’s unified ambition to reach the heavens is interrupted by divine intervention. Language is confounded, and the people are scattered—ambition halted by humility.\nToday, we are building again. But this time, the tower is digital.\nA New Kind of Tower Generative AI has evolved from novel concept to global phenomenon in under two years. According to McKinsey, 79% of professionals have used generative AI, and 40% of companies plan to increase investment because of it. It’s not just a tool—it’s becoming infrastructure.\nLike Babel, the AI revolution is underpinned by a common tongue: programming languages, machine learning models, and vast data sets shared across borders.\nBut if language once unified us, today it might divide us again.\nWhen Truth Becomes Output AI systems don’t know truth—they generate plausible output. And yet, many of us trust them to write job descriptions, flag criminal risk, draft news summaries, and moderate online discourse.\nIn one widely used AI legal system (COMPAS), Black defendants were twice as likely to be wrongly labelled “high risk” compared to white defendants.\nLess than 32% of companies using generative AI are actively addressing its risk of inaccuracy\nAI tools like ChatGPT can produce elegant lies, mistaken citations, and confident hallucinations—often accepted as fact by users.\nWhat happens when truth is no longer verified, but assumed from an algorithm’s answer?\nMachines Can Judge, But Not Conscience A key difference between human judgement and machine output is empathy. AI does not feel remorse. It cannot be held accountable. It does not understand suffering.\nAnd yet, we are deploying it in:\nJudicial settings (bail, sentencing recommendations) Hiring and firing decisions Medical triage Political content moderation “An algorithm can replicate moral reasoning, but it cannot possess moral responsibility.”\nJust because AI can decide, doesn’t mean it should.\nParallels With Babel Babel Today’s AI Landscape One language united humanity Shared AI platforms and coding languages Tower to reach the heavens Drive toward artificial general intelligence Collapse from confusion Fragmentation through misinformation and automation bias Human ambition without humility AI ambition without ethical guardrails In both cases, the pursuit of greatness lacked grounding in wisdom and restraint.\nThe Risks of Letting Go The Tower of Babel failed because people tried to unify around something they didn’t fully understand. Similarly, today’s overreliance on AI risks:\nAutomation bias: deferring to AI even when it’s wrong Opacity: not knowing how decisions were made Moral displacement: letting machines guide decisions that require empathy Erosion of accountability: no clear person responsible for AI decisions Without deliberate human oversight, we risk building systems that scale injustice, not eliminate it.\nWhat Should We Do Differently? Not halt AI—but build it better. The lesson from Babel isn’t to stop building—it’s to build with wisdom, humility, and shared ethics.\nThat means: Embedding human-in-the-loop systems\nEnsuring transparency and explainability\nEstablishing ethical AI design standards\nPreserving conscience as the ultimate decision-maker\nAs Bryan Avery’s AI readiness model puts it:\n“Artificial intelligence applied when needed. Emotional intelligence applied as standard.”Unlocking Opportunities with AI…\nFinal Thought If we let AI define truth and justice, we risk forgetting how to hear the still, small voice of human conscience. And once that voice is quieted, the machine won’t bring it back.\nLet us not build a tower that forgets the ground beneath our feet.\nReferences:\nMicrosoft Copilot adoption and ethical AI design\nhttps://link.technologyadvice.com/r/microsoft-copilot-tr-microsoft-copilot-cheat-sheet\n– Covers how Microsoft’s AI tools are being deployed and the standards around responsible use.\nMcKinsey’s Global AI Survey (2024): AI adoption and risk\nhttps://www.mckinsey.com/capabilities/mckinsey-digital/our-insights/the-state-of-ai-in-2023-generative-ais-breakout-year\n– Documents business usage trends, governance concerns, and ethical gaps in generative AI deployment.\nMicrosoft Responsible AI Standard v2 (2023)\nhttps://www.microsoft.com/en-us/ai/responsible-ai\n– Outlines guiding principles on fairness, accountability, and human oversight in AI systems.\n","date":"16 December 2025","externalUrl":null,"permalink":"/the-tower-of-babel-rebuilt-are-we-creating-a-god-in-the-machine/","section":"Articles","summary":"The Ancient Warning “Come, let us build ourselves a city, with a tower that reaches to the heavens… so that we may make a name for ourselves.”\n— Genesis 11:4\nIn the biblical story of the Tower of Babel, humanity’s unified ambition to reach the heavens is interrupted by divine intervention. Language is confounded, and the people are scattered—ambition halted by humility.\n","title":"The Tower of Babel Rebuilt: Are We Creating a God in the Machine?","type":"articles"},{"content":"As artificial intelligence permeates everyday life, society faces a provocative question: are we ceding our definitions of truth and justice to machines? From AI-powered news feeds that shape what we see as “true” to algorithms advising judges on sentences, the influence of AI on moral and legal decisions is growing. Tech giants tout AI systems – from generative chatbots like ChatGPT to decision tools in courts and HR departments – as unbiased and efficient. Yet observers worry that by increasingly relying on AI to decide what is true and what is fair, we risk outsourcing our own moral judgement. Could an AI, even one designed to sound human, ever replace the human conscience that guides ethical decisions? This article explores the consequences of this shift, drawing on expert insights and current examples to challenge readers to critically consider how far we should entrust truth and justice to algorithms.\nAI-Generated “Truth” and the Risk of Misinformation Artificial intelligence is already a powerful gatekeeper of information. Generative AI models can produce confident answers and realistic content on demand – but that doesn’t guarantee truth. In fact, 77% of businesses express concern about AI “hallucinations” – the tendency of AI like large language models to invent false information – and 47% of enterprise AI users admitted making at least one major decision based on AI-generated false content in 2024 fullview.io. The convenience of an AI assistant that can answer any question or draft any report also brings a deceptive aura of authority. Users may assume that if an answer is detailed and fluent, it must be correct, blurring the line between accuracy and truth. A United Nations University analysis warns that “when accuracy is confused with truth, there is a high risk of harm, especially in fields where human judgment and ethical considerations are critical.”unu.edu In other words, an AI system can be technically accurate according to its training data and still be fundamentally untrue or misleading in context – a dangerous scenario if we start accepting AI outputs uncritically as the “ground truth.”\nThis risk is far from hypothetical. ChatGPT and similar generative AI tools have already been caught confidently fabricating facts, yet they are rapidly being adopted in workplaces and media. Less than a year after its debut, 92% of Fortune 500 companies had employees using ChatGPT for assistance fullview.io. Overall AI adoption has surged – 78% of organizations now use AI in at least one business function, up from 55% in 2023 fullview.io – but governance lags behind. One industry survey in 2025 found that only 27% of companies review all generative AI outputs before release; most rely on spot checks or trust the AI by default workforcesolutionsnews.com. In effect, many organisations are letting algorithms define information presented as fact, without fully vetting the results. That approach can backfire spectacularly: consider the embarrassment of a legal team that submitted an AI-written brief citing nonexistent cases, or a medical chatbot offering unsound health advice that a human professional would instantly flag. Such incidents underscore that AI’s “knowledge” is ultimately a reflection of its training data and programming – not an independent arbiter of truth. If we allow AI systems to become authoritative sources by virtue of their ubiquity, we risk a future where facts are whatever an algorithm outputs, and errors or biases at scale could misinform millions.\nAI’s role in content moderation and online discourse also raises red flags. Social media platforms deploy AI filters to decide what speech is permissible or which posts get promoted. These algorithms, while faster than human moderators, can carry hidden political or cultural biases. For example, an analysis of one AI content moderation system found it flagged identical derogatory comments differently depending on the target – negative comments about women were much more often tagged as “hateful” than the same comments about men manhattan.institute. And the system was more permissive of hateful remarks aimed at conservatives than the exact same slurs directed at liberals, suggesting an embedded political tilt manhattan.institute. If such automated gatekeepers consistently err in one direction, they could silently skew public discourse. Indeed, some researchers caution that if AI systems like chatbots or recommendation algorithms become ubiquitous while carrying systematic political biases, they may increase societal polarisation manhattan.institute. The prospect of AI-defined “truth” is thus double-edged: on one hand, AI might counter human misinformation by quickly debunking falsehoods; on the other, it might produce convincing falsehoods or biased outputs of its own. The critical question is whether we will have the wisdom and transparency to discern the difference.\nAlgorithmic Justice: AI in Law and the Courts Perhaps nowhere is the tension between AI efficiency and human conscience more stark than in the justice system. Courts around the world have begun experimenting with AI tools – from risk assessment algorithms that guide judges in sentencing and bail decisions to AI systems that research case law or even draft judgments. Supporters argue that AI can make legal outcomes more consistent and free from human prejudices. However, when it comes to defining justice, the limitations of these systems are alarming. Criminal sentencing provides a cautionary tale: A widely used algorithm in US courts, COMPAS, analyzes defendants’ data to predict their likelihood of reoffending. While the goal is to aid judges with data-driven objectivity, in practice COMPAS demonstrated troubling racial bias. A landmark ProPublica investigation found the tool was almost twice as likely to falsely label Black defendants as high-risk compared to white defendants rev.com. In other words, an algorithm purported to improve fairness was systematically harsher on one group, reflecting biases in the underlying data (historical crime and policing records) rather than any objective reality of “dangerousness.” This sparked a debate nationwide about bias in “algorithmic justice” and whether such tools inadvertently encode and legitimize the very disparities the legal system seeks to eliminate.\nCourts have wrestled with how to incorporate these AI recommendations. In the 2016 State v. Loomis case, the Wisconsin Supreme Court allowed the use of COMPAS scores in sentencing decisions but warned judges not to rely on them exclusively, acknowledging both the tool’s potential utility and its serious limitations rev.com. This illustrates a vital point: AI might assist human decision-makers, but it cannot replace them in moral and legal reasoning. The human judge bears responsibility to temper data with judgment. Indeed, the ongoing evidence suggests that without careful checks, AI may simply make biased or unjust decisions faster. A 2024 study by Tulane University found that an AI-assisted sentencing system, while reducing jail time on average for some low-risk offenders, still disproportionately flagged minority defendants as high risk – effectively automating unequal treatment under the law rev.com. As the study dryly noted, unless we resolve these bias issues, AI tools may only make unfair sentencing “faster,” not fairer rev.com.\nBeyond sentencing, AI is being eyed for roles like evaluating evidence or even acting as a virtual judge in small disputes, raising further ethical questions. Legal experts emphasize that justice is not just a data problem to optimize. It involves empathy, context, mercy, and the nuanced application of values – factors an algorithm struggles to grasp. “The challenge is to balance innovation with justice; the tools must support – not replace – the human judgement so central to a fair legal system,” writes legal analyst Luke Daugherty rev.com. Efficiency cannot come at the cost of equity. An AI might calculate a recidivism risk score with great precision, but it cannot appreciate the individual story behind a defendant or the moral weight of punishing versus forgiving. Nor can it be held accountable in the way society expects of a human judge or juror. In the realm of law, an unjust decision – even if efficiently arrived at – is not true justice at all. This is why many jurists insist that algorithms in court be kept on a short leash: useful for insight, perhaps, but ultimately subordinated to human conscience and common sense.\nAlgorithms at Work: AI in Hiring and Social Decisions The push to hand off decision-making to AI is not limited to courts or content feeds – it’s happening in workplaces and society at large. Human resources departments, for instance, have turned to AI tools to screen CVs, rank job candidates, and even predict employee performance. The promise is tempting: removing human bias and gut-feel from hiring could yield fairer, merit-based decisions. The reality, however, has often been the opposite. A famous example came from Amazon, which developed an experimental AI recruiting engine to streamline hiring. The result? Amazon’s machine-learning tool taught itself that male candidates were preferable to female ones, because it was trained on ten years of resumes the company received – most of which came from men in the male-dominated tech industry reuters.com. The AI system began penalising resumes that contained the word “women’s” (as in “women’s chess club captain”) and downgraded graduates of women’s colleges reuters.com. In effect, the algorithm imbibed past bias and regurgitated it as an objective hiring criterion. Amazon’s engineers tried to correct for this once the issue was discovered, but they rightly lost confidence – if the AI wasn’t explicitly sexist, it might find other, more subtle ways to discriminate. The project was scrapped before it could do real harm, but it serves as a stark warning: without extreme care, AI decision tools can simply automate old prejudices under a veneer of algorithmic impartiality.\nThis problem is not just theoretical. Regulators are increasingly alert to AI-driven discrimination. In one case, a company called iTutorGroup faced action from the U.S. Equal Employment Opportunity Commission after its hiring algorithm was found to be rejecting older applicants en masse, purely based on age – a blatant violation of employment law workforcesolutionsnews.com. The incident showed how an AI designed to optimise a hiring process can collide with human values and legal standards (in this case, age diversity and anti-discrimination laws). It’s a reminder that “efficient” outcomes by an AI are not necessarily equitable outcomes. Hiring and firing affect livelihoods and dignity, and involve ethical judgments about bias, diversity, and second chances that a narrow AI metric might not capture. If managers simply defer to an algorithm’s recommendations (“the computer says this applicant isn’t a good fit”), there is a risk that meaningful human oversight and fairness checks fall by the wayside.\nAI’s influence on social and political decisions is also fraught with unintended consequences. We’ve seen social media algorithms, guided by AI, amplify certain types of content to maximise engagement – sometimes to society’s detriment by spreading outrage or misinformation. AI moderation tools can likewise err. They might mistakenly flag satire or activism as “hate speech” or “disinformation”, or conversely fail to catch harmful content if it’s phrased in a way the AI doesn’t recognise manhattan.instituteoversightboard.com. This raises thorny questions: Who defines the community standards these AIs enforce, and what happens when the AI gets it wrong? Unlike a human moderator, an AI cannot easily be reasoned with or asked for an explanation; its judgment is often a black box. Moreover, the scale is immense – an automated system making thousands of moderation decisions per second could shape the very landscape of public discourse without most users realising it. If we allow AI systems to become the de facto arbiters of what can be said (and by whom) in digital society, we risk normalising a kind of algorithmic governance that lacks transparency and appeals process. In political contexts, this could be dangerous: imagine an AI inadvertently biased against a certain vernacular or culture controlling which political ads are approved, or which grassroots posts are suppressed. The result could tilt the playing field of democracy. In short, while AI can help manage the enormous scale of modern digital life, ceding too much control to it in social decisions might undermine the human values – like free expression and fairness – that we seek to uphold.\nThe Human Conscience vs. the Algorithm Why can’t an advanced AI serve as a perfectly logical judge or an unbiased hiring manager? The fundamental reason is that AI lacks the very qualities that constitute a moral conscience. An AI, no matter how sophisticated, is not a sentient being with empathy, compassion, or an inherent sense of right and wrong. As one philosopher put it, “AI itself cannot be a moral agent” – it can mimic decision-making but cannot truly understand the moral weight of its choices stories.tamu.edu. Unlike humans, an AI has no free will or awareness; it follows its programming and data patterns. This means if an AI system causes harm, the blame lies not on the machine – which has no concept of blame – but on its human creators and operators stories.tamu.edu. In essence, an AI can produce the same outputs a human might, but it does so without understanding. It will not lose sleep over an unfair verdict it recommended, or feel remorse if its recommendation inflicts suffering. A human judge or manager, imperfect as they are, can at least strive to act conscientiously and live with the moral consequences; a machine cannot.\nThis gap between computation and conscience gives rise to several inherent limitations of AI-driven decisions in ethical domains:\nLack of Context and Insight: AI systems are context-blind. They excel at detecting patterns in the data they are given, but they lack a full understanding of real-world nuances, cultures, and individual circumstances cometanalysis.com. For instance, an algorithm might note a person has had three job changes in two years and flag them as a “risk,” whereas a human might discover those moves were due to family caregiving needs – a factor of human life no algorithm would infer from raw data. Human judgment can incorporate intangible context; AI cannot truly step outside its programmed parameters. No Genuine Empathy or Mercy: Human conscience allows for empathy – the ability to put oneself in another’s shoes – and for mercy – the choice to give someone a second chance or the benefit of the doubt. AI lacks these faculties entirely. It cannot understand pain, hope, or ethical duty. This is why, for example, philosophers caution against overreliance on AI in roles like mental health support or education, where empathy and “practical wisdom” (what Aristotle called phronesis) are crucial stories.tamu.edustories.tamu.edu. An AI might simulate a friendly counsellor well, but we shouldn’t be fooled into thinking the AI ‘understands’ us in any human sense stories.tamu.edu. Bias In, Bias Out: Despite hopes that AI would be more objective than humans, it inevitably inherits biases present in its training data. If historical data reflect social biases, the AI will likely perpetuate them unu.edu. Moreover, AI’s notion of “fair” is only as good as the mathematical criteria we define – which are hotly debated, as seen in the COMPAS example. AI has no innate moral compass to detect bias; only careful human oversight can identify and correct it, and even that is challenging when the AI’s decision process is opaque. False Confidence and Automation Bias: AI systems often present their outputs with supreme confidence – a neatly calculated score, a definitive recommendation – giving users a false sense of certainty cometanalysis.com. This can lure humans into what experts call automation bias: a tendency to trust the machine’s decision more than one’s own judgment. For instance, pilots and doctors have been known to occasionally override their own instincts in deference to an automated system (sometimes with dire results). In corporate or legal settings, a manager might accept an AI’s flawed recommendation without question because it looks data-driven and authoritative cometanalysis.com. Such deference is dangerous. As AI ethicist Tshilidzi Marwala notes, high accuracy in output is not the same as truth or wisdom – and confusing the two can lead to serious harm unu.eduunu.edu. Critical thinking and healthy skepticism are needed more than ever when dealing with AI outputs. Accountability Gaps: With human decision-makers, we expect accountability – a judge must justify a ruling, a CEO can be fired for poor decisions. But when an AI system makes a decision or prediction, who is accountable if it goes wrong? The responsibility technically falls to the humans deploying it, but in practice this can become a grey area. Companies have sometimes deflected blame by saying “the algorithm made a mistake,” as if that absolves them. Society has yet to fully work out legal and moral accountability in cases where AI systems cause harm. What is clear is that an AI itself cannot be “accountable” in the way a person is – it cannot answer for its actions or learn a moral lesson from an error. This means any system where AI plays a major role must build in human accountability and the ability for humans to override or question the machine. Otherwise we end up with decisions made by unanswerable black boxes, a scenario no ethical society should accept. Each of these limitations illustrates why human conscience and oversight remain indispensable. We can delegate number-crunching and data-sifting to machines, but delegating moral reasoning is another matter. As one safety engineering firm concluded after studying AI in high-risk industries: AI should augment human expertise, not automate it, in any arena where lives, rights or livelihoods are on the line cometanalysis.comcometanalysis.com. Even the most advanced AI lacks the holistic understanding, ethical intuition, and sense of responsibility that a human decision-maker brings. Our challenge is to harness AI’s strengths – consistency, speed, analytical power – without relinquishing the human values and judgment that define justice and truth.\nStriving for Responsible AI: Keeping Humans in the Loop Given the profound risks and limitations outlined above, how are we as a society responding? Both governments and businesses are waking up to the need for responsible AI practices that ensure these technologies are used in alignment with human values. Around the world, regulators are drafting rules to rein in AI’s dangers while preserving its benefits. The European Union has led the way with a comprehensive AI Act, a risk-based regulatory framework that will impose strict requirements on “high-risk” AI systems (such as those used in law enforcement, hiring, or credit scoring) to ensure they are transparent, explainable, and free from prohibited biases. In contrast, the United Kingdom so far favours a more “light-touch” approach, avoiding sweeping AI-specific laws in favour of guidance and existing regulations – though the UK government has signalled it will regulate the most powerful AI models soon epthinktank.euepthinktank.eu. Both approaches seek a balance: foster innovation in AI, but not at the expense of rights and safety. Likewise, the United States is exploring AI oversight, from the White House’s non-binding AI Bill of Rights blueprint to various legislative proposals, aiming to prevent AI-driven discrimination and ensure AI systems are auditable. Notably, dozens of countries (including EU members, the UK, and the US) have also signed onto international agreements like the Council of Europe’s Convention on AI and Human Rights, pledging to develop AI in ways that uphold equality, democracy and the rule of law epthinktank.eu.\nCorporate players, too, recognize that trust in AI is essential and fragile. In the wake of AI controversies, many tech companies have published their own ethical AI principles. Common themes have emerged – fairness, transparency, accountability, privacy, and security are often cited as the five key pillars of responsible AI use professional.dce.harvard.edu. In practical terms, these principles mean companies are committing (at least on paper) to test their algorithms for bias, explain their AI’s decision logic where possible, protect user data, and maintain human oversight. For example, IBM has an AI Ethics Board to review sensitive projects, Google famously developed AI ethics guidelines (like avoiding applications that violate human rights), and Microsoft established an Office of Responsible AI to integrate ethical considerations into product development. The reality of implementation can be messy – there have been instances of companies disbanding ethics teams or rushing AI features to market despite internal objections – but the trend indicates growing awareness that unchecked AI development poses reputational and legal risks. A Harvard analysis notes that businesses racing ahead with AI without governance face “bruised reputations, stakeholder divestment, [and] talent flight” if things go wrong professional.dce.harvard.edu. In other words, it’s in a company’s own interest to avoid an AI scandal where their tool is found to be biased or harmful.\nConcrete measures are emerging. Firms are beginning to conduct bias audits on AI models, use more diverse training data, and implement “human-in-the-loop” systems where AI suggestions must be reviewed and approved by people. Many organisations now train staff on the limitations of AI and how to use it ethically workforcesolutionsnews.com. Some are even buying insurance against AI failures and creating incident response plans for AI glitches. Yet, a gap remains between principle and practice. Surveys show that while companies acknowledge AI risks, most have not fully addressed them – for instance, only about 21% of companies using AI have established policies guiding employees on proper AI use at work, and less than half are actively mitigating even the AI risks they deem most relevant mckinsey.com. It appears we are in the early days of developing an AI “conscience” in our institutions. The intentions are there, but robust safeguards and oversight mechanisms are still catching up with the breakneck pace of AI adoption.\nUltimately, the goal of responsible AI efforts is not to halt progress, but to ensure progress doesn’t steamroll over human values. Government rules and corporate ethics charters alike seek to draw lines: for example, saying an AI should assist a judge but never hand down a sentence on its own, or that an AI hiring program must be auditable for bias and subject to human review before rejecting candidates. These checks and balances are about keeping humans in control. As one industry safety report put it, even as AI grows more capable, “certain decisions should always remain in human hands.” cometanalysis.comcometanalysis.com That speaks to a widely held conviction: We can enjoy the efficiency and insights of AI, but when it comes to decisions of truth and justice – decisions that shape lives and society – we should not abdicate responsibility. Instead, AI should be a tool that operates under the guidance of human conscience. The hope is that with smart regulation, transparent design, and a culture of ethical awareness, we can harness AI in ways that enhance human judgement – for example, by catching inconsistencies or offering data-driven perspectives – without replacing the intangible moral and emotional intelligence that makes us human.\nConclusion: A New Age of Wisdom or Worry? The rise of AI in defining truth and justice presents us with both exciting opportunities and disquieting dilemmas. On one hand, we have at our disposal tools of unprecedented power – algorithms that can sift truth from lies across billions of documents in seconds, or predictive models that could help judges and managers make more informed, consistent decisions. There is a genuine hope that, used wisely, AI could reduce human errors, cut through personal prejudices, and point us toward fairer outcomes. On the other hand, as we have seen, these tools are fundamentally limited by the absence of human conscience and understanding. They can as easily scale up biases as eliminate them. They can give an illusion of objectivity and overwhelm our critical faculties. And they raise the spectre of moral abdication: that we might gradually stop exercising our own judgement and compassion, content to let machines decide what is true or just.\nSo will artificial intelligence supplant human moral judgement? The most honest answer today is: only if we let it. AI cannot “replace” the human conscience in any literal sense – a machine does not possess empathy, guilt, love, or principles – but we can certainly choose to ignore our conscience and follow the machine’s outputs blindly. The controversial, thought-provoking challenge before us is to resist that temptation. As individuals, that means staying informed and skeptical about AI-generated information, and remembering that truth requires human context and verification. As communities and organisations, it means insisting on human accountability and oversight for AI-driven decisions. As a society, it may mean drawing red lines (through laws or norms) about decisions that we refuse to delegate to AI, no matter how advanced – be it final say in criminal sentencing, life-and-death medical triage, or other profoundly human judgements.\nIn the end, truth and justice are not mere computational problems; they are products of human values, debate, and yes, sometimes human imperfection. An algorithm might analyse past data to suggest an answer, but it takes a human conscience to ask “Should we?” rather than just “Can we?”. Perhaps the real promise of this AI age is not that machines will render us morally obsolete, but that they will force us to reaffirm the very qualities that make us human. By confronting us with ultra-rational, unfeeling decision-makers, AI can highlight the importance of empathy, context, and moral responsibility in our choices. The hope is that we will rise to the occasion – using AI to inform and improve our judgement, but never to erase it. As we stand at this crossroads, the ultimate verdict on AI’s role in truth and justice will depend on our collective vigilance and wisdom. It’s a test of conscience for all of us: will we let convenience and automation numb our moral instincts, or will we critically engage with these tools and ensure they reflect our highest values? The answer may well determine the character of our society in the years to come.\n","date":"16 December 2025","externalUrl":null,"permalink":"/ai-as-arbiter-of-truth-and-justice-can-algorithms-supplant-human-conscience/","section":"Articles","summary":"As artificial intelligence permeates everyday life, society faces a provocative question: are we ceding our definitions of truth and justice to machines? From AI-powered news feeds that shape what we see as “true” to algorithms advising judges on sentences, the influence of AI on moral and legal decisions is growing. Tech giants tout AI systems – from generative chatbots like ChatGPT to decision tools in courts and HR departments – as unbiased and efficient. Yet observers worry that by increasingly relying on AI to decide what is true and what is fair, we risk outsourcing our own moral judgement. Could an AI, even one designed to sound human, ever replace the human conscience that guides ethical decisions? This article explores the consequences of this shift, drawing on expert insights and current examples to challenge readers to critically consider how far we should entrust truth and justice to algorithms.\n","title":"AI as Arbiter of Truth and Justice: Can Algorithms Supplant Human Conscience?","type":"articles"},{"content":"If your business runs a website, customer portal, booking system, online shop, or internal web-based tool, then web application security is not optional. Web applications are one of the most common entry points for cyber attacks because they are public-facing, interactive, and often connected to sensitive data.\nThis article explains, how web applications are attacked, what actually protects them, and how businesses should think about security using proven OWASP principles.\nWhy web applications are such a common target A web application is more than just a “website”. It includes login pages, contact forms, payment systems, APIs, admin dashboards, and anything that processes requests over the internet.\nAttackers don’t usually need to break in dramatically. They look for small weaknesses: a form that doesn’t validate input properly, an error message that reveals too much information, or a forgotten system that was never patched. Once found, these weaknesses can be exploited automatically and at scale.\nThe goal of web application security is to prevent data theft, service disruption, regulatory breaches, and reputational damage before they happen.\nSecure design starts long before launch One of the biggest mistakes organisations make is treating security as something to “add later”. Security needs to be part of how an application is designed, built, tested, and maintained.\nDecisions made early, such as how users log in, how data is checked, how long sessions last, and what gets logged, have a long-term impact on risk. Fixing security issues after an application is live is slower, more expensive, and far more disruptive.\nGood security design saves money in the long run.\nNever trust user input Every piece of data a web application receives should be treated as untrusted. This includes form fields, URLs, cookies, hidden fields, uploads, and API requests.\nApplications must check that input:\nis the correct type is within an acceptable range is the expected length and format They must also clean or neutralise input so it cannot be interpreted as executable code. Many common attacks, such as cross-site scripting and injection attacks, succeed simply because applications trust what users send them.\nImportantly, these checks must happen on the server. Anything that relies only on the web page itself can be bypassed.\nSecurity must never rely on users clicking buttons in the “right order”. Attackers do not use the interface in the way it was intended. They send crafted requests directly to the server.\nThis is why all critical checks, including authorisation and validation, must be enforced server-side.\nError messages, sessions, and access control matter more than people think Small details often create big risks.\nError messages should be generic and never expose technical information. Session timeouts reduce the chance of account hijacking, especially on shared or compromised devices. Session identifiers must be unpredictable and only transmitted securely.\nAccess should follow the principle of least privilege. Users and systems should only have the permissions they genuinely need. Logging failed logins and access attempts is essential for detecting misuse and investigating incidents.\nWeb Application Firewalls: a vital layer of defence A traditional firewall controls traffic based on ports and IP addresses. A Web Application Firewall (WAF) goes much further by understanding web traffic itself.\nA WAF inspects HTTP and HTTPS requests and can detect and block common attack patterns such as:\ncross-site scripting SQL injection cross-site request forgery directory traversal application-layer denial-of-service attacks WAFs also provide centralised visibility into attack attempts, helping organisations spot trends and respond early.\nHowever, a WAF is not a replacement for secure design. It works best as part of a layered security approach.\nCloud-based protection and smart configuration In cloud environments, WAFs are typically provided as managed services. These often support a detection mode, which logs suspicious activity, and a prevention mode, which actively blocks attacks.\nDetection is useful when tuning rules to avoid disrupting legitimate users. Prevention provides stronger protection once confidence is established. Modern platforms use OWASP-aligned rule sets that evolve as new threats emerge.\nScanning: seeing what attackers can already see Anything exposed to the internet can be discovered. Regular scanning helps organisations see themselves as an attacker would.\nNetwork scanning identifies which systems are reachable and which services are exposed. Vulnerability scanning goes further by identifying known weaknesses such as missing patches, weak configurations, or insecure protocols.\nThese scans do not exploit systems. They highlight what needs fixing and allow teams to prioritise work based on risk.\nPenetration testing: proving real-world impact Penetration testing takes things a step further by actively attempting to exploit weaknesses. This helps answer a critical question: if this issue is abused, what actually happens?\nPen testing can reveal whether attackers could access sensitive data, bypass controls, or disrupt services. Because it can affect live systems, it must be carefully planned, authorised, and governed.\nIt is different from broader attack simulations, which focus on how well an organisation detects and responds rather than purely technical flaws.\nSecurity is a process, not a one-off task Strong web application security comes from combining good design, preventative controls, and continuous testing.\nOrganisations that follow OWASP-aligned practices typically:\nbuild security into applications from the start protect exposed systems with WAFs scan regularly for weaknesses carry out periodic penetration testing patch and update quickly log and monitor activity This layered approach dramatically reduces risk.\nFinal thoughts Web application security is about protecting your business, not just your technology. As applications evolve and threats change, security must evolve with them.\nBy designing securely, protecting intelligently, and testing regularly, organisations can safeguard data, maintain availability, and build trust with customers and partners. OWASP principles provide a practical, proven foundation for doing exactly that.\n","date":"15 December 2025","externalUrl":null,"permalink":"/web-application-security-what-every-business-needs-to-get-right/","section":"Articles","summary":"If your business runs a website, customer portal, booking system, online shop, or internal web-based tool, then web application security is not optional. Web applications are one of the most common entry points for cyber attacks because they are public-facing, interactive, and often connected to sensitive data.\n","title":"Web Application Security: What Every Business Needs to Get Right","type":"articles"},{"content":"","date":"11 December 2025","externalUrl":null,"permalink":"/categories/agentic/","section":"Categories","summary":"","title":"Agentic","type":"categories"},{"content":"Artificial intelligence is evolving quickly, but one of the most important shifts happening right now is the move towards agentic AI—systems capable of planning, reasoning and acting with a degree of autonomy. They can simulate outcomes, test strategies, and help humans make more informed decisions.\nIt’s a transformative step forward, but it only works if the technology is designed with people firmly at the centre.\nBeyond Automation: Unlocking Human Capability Traditional AI often focuses on efficiency: automating tasks, streamlining processes, removing repetitive work. Agentic AI goes further. It aims to enhance human capability by:\npredicting complex outcomes using dynamic simulations surfacing strategic insight leaders would struggle to see alone functioning as a “what-if machine” to explore scenarios safely helping people make decisions with more clarity and foresight Rather than replacing human judgment, agentic systems are meant to augment it—effectively giving people “superpowers” by expanding what they can know and anticipate.\nThe Hidden Impact: Why Social Awareness Is Essential A recurring theme in the field is the danger of designing AI only for the immediate end user. It’s easy to overlook how a system’s behaviour can ripple outwards and affect:\ncolleagues communities entire industries society at large History is full of examples where a well-intentioned piece of technology solved one problem but unintentionally created another. Autonomous systems can shift power dynamics, influence behaviour, or reshape patterns of daily life—often in ways their designers never predicted.\nBecause of this, agentic AI must consider not only who will use the system, but who else might be affected.\nHuman-in-the-Loop: A Safeguard Against Misalignment As AI becomes more autonomous, the risk of misaligned objectives grows. Even small errors can carry outsized consequences when decisions are made at scale or involve sensitive outcomes.\nKeeping humans meaningfully involved—especially in high-impact areas—is one of the most effective ways to ensure:\nalignment with human intent the ability to intervene when something seems off accountability and traceability trustworthiness Human oversight isn’t a limitation; it’s a foundation for safe autonomy.\nCollaboration Across Disciplines Building responsible agentic systems isn’t only a technical challenge. It requires insight from behavioural science, ethics, social sciences, regulation, and lived human experience.\nThe most effective solutions are shaped by diverse perspectives, each illuminating risks or opportunities the others miss.\nMeasuring What Really Matters Efficiency metrics alone no longer tell the whole story. Intelligent systems must be evaluated on:\nhuman agency wellbeing inclusiveness clarity and transparency An AI system is successful not only when it works quickly, but when it works fairly, explainably, and in harmony with human values.\nThe Future: AI That Amplifies, Not Overrules Agentic AI represents a major step forward, but its potential is only realised when the technology supports and elevates human capability. Done well, it helps us make decisions with greater confidence, navigate uncertainty more effectively, and understand the wider consequences of our actions.\nThe goal isn’t to replace people.\nThe goal is to create systems that help us think better, act wiser, and build solutions that benefit everyone—not just those at the centre of the screen.\n","date":"11 December 2025","externalUrl":null,"permalink":"/agentic-ai-why-human-centred-design-matters-more-than-ever/","section":"Articles","summary":"Artificial intelligence is evolving quickly, but one of the most important shifts happening right now is the move towards agentic AI—systems capable of planning, reasoning and acting with a degree of autonomy. They can simulate outcomes, test strategies, and help humans make more informed decisions.\n","title":"Agentic AI: Why Human-Centred Design Matters More Than Ever","type":"articles"},{"content":"Introduction Software development has evolved rapidly, and with it, the need for robust security practices has never been greater. Across industries, organizations are embracing DevSecOps—a methodology that integrates security into every stage of the development lifecycle. This shift is essential because open-source adoption has skyrocketed, growing from just 36% of codebases in 2015 to 75% in 2020. While this trend accelerates innovation, it also introduces significant risks. High-profile breaches, such as the SolarWinds attack, have demonstrated how vulnerable the software supply chain can be when security is not prioritized.\nTo address these challenges, Artificial Intelligence (AI) is emerging as a transformative force, enabling DevSecOps teams to move from reactive security measures to proactive, intelligent protection.\nThe Role of Software Composition Analysis One of the most critical components of modern DevSecOps is Software Composition Analysis (SCA). SCA tools help organisations identify vulnerabilities in open-source and third-party components, enforce compliance with licensing requirements, and generate Software Bills of Materials (SBOMs), a key requirement for many regulatory frameworks and government contracts. These capabilities are vital for maintaining transparency and trust in the software supply chain.\nHowever, implementing SCA at scale is not without challenges. Many leading tools struggle to support air-gapped environments, which are common in highly secure deployments. Maintaining separate solutions for connected and disconnected environments can be costly and operationally complex. Additionally, even minimal data shared externally, such as fingerprints of open-source packages, can expose sensitive information about an organization’s technology stack.\nHow AI Transforms DevSecOps AI introduces intelligence and automation into every stage of the DevSecOps pipeline. Instead of relying solely on static scans and manual reviews, AI-driven systems can analyze patterns, predict risks, and recommend solutions in real time.\nFirst, AI enhances vulnerability detection by identifying risky dependencies and predicting emerging threats based on historical exploit trends. It also improves risk prioritisation, ranking vulnerabilities by exploit likelihood and business impact so teams can focus on the most critical issues. When it comes to remediation, AI offers smart suggestions, recommending safe patches or alternative libraries and validating compatibility to reduce the risk of breaking builds.\nAI also plays a key role in compliance monitoring. By mapping open-source usage against industry standards and organizational policies, AI can automate license checks and generate SBOMs without manual intervention. In addition, AI strengthens supply chain security by detecting anomalies in dependency graphs and flagging suspicious packages, helping prevent attacks like dependency confusion.\nFor organizations operating in air-gapped environments, AI can even forecast update cycles and optimize data transfer schedules, reducing manual effort and ensuring systems remain secure.\nThe AI-Augmented DevSecOps Pipeline AI can be embedded throughout the DevSecOps lifecycle. During development, it provides secure coding suggestions and automatically generates SBOMs. In the build phase, AI performs vulnerability scanning and dependency risk analysis. During testing, it prioritizes issues and recommends safe fixes. At deployment, AI predicts risks and validates supply chain integrity. Post-deployment, AI continuously monitors for anomalies and enforces compliance. Finally, AI supports proactive threat intelligence and policy automation to maintain security over time.\nBest Practices for Industry Adoption To fully leverage AI in DevSecOps, organizations should integrate AI-driven security checks early in the development process. Automating SBOM generation ensures compliance and transparency, while hybrid strategies can balance connectivity for both online and air-gapped environments. Finally, strict governance policies should be implemented to manage any external data sharing.\nConclusion AI is no longer a luxury, it is a necessity for modern DevSecOps. By embedding intelligence into vulnerability detection, compliance, and remediation workflows, organizations can achieve a proactive security posture, reduce operational overhead, and safeguard the software supply chain against evolving threats.\n","date":"8 December 2025","externalUrl":null,"permalink":"/ai-augmented-devsecops-securing-the-software-supply-chain-at-scale/","section":"Articles","summary":"Introduction Software development has evolved rapidly, and with it, the need for robust security practices has never been greater. Across industries, organizations are embracing DevSecOps—a methodology that integrates security into every stage of the development lifecycle. This shift is essential because open-source adoption has skyrocketed, growing from just 36% of codebases in 2015 to 75% in 2020. While this trend accelerates innovation, it also introduces significant risks. High-profile breaches, such as the SolarWinds attack, have demonstrated how vulnerable the software supply chain can be when security is not prioritized.\n","title":"AI-Augmented DevSecOps: Securing the Software Supply Chain at Scale","type":"articles"},{"content":"Businesses of every size are now moving far beyond early AI experimentation. What began with simple copilots and isolated proof-of-concepts has quickly evolved into a landscape where organisations expect to operate dozens—and soon thousands—of AI agents across their departments. These agents will collaborate with one another, call internal and external systems, interpret complex contexts and support increasingly critical business processes. As this shift accelerates, one question becomes unavoidable: how do we allow AI to scale without losing control, breaching compliance, duplicating effort or suffocating innovation?\nThis is the challenge Microsoft’s Citadel Governance Hub is designed to address. Citadel provides a ready-made, production-grade landing zone for AI apps and agents—one that enables speed and creativity while imposing the structure and safeguards that modern enterprises require. It brings order, consistency and visibility to environments that, without central governance, quickly become fragmented, unmanageable and risky.\nCitadel works by introducing a clear architectural backbone for AI across the organisation. Instead of every team spinning up its own AI endpoints, storing keys in different places and rebuilding the same tools repeatedly, Citadel creates a central governance hub that all agents flow through. This hub acts as a trusted, auditable gateway for every model, tool and shared agent, ensuring that each request follows the same security, privacy and policy rules. For businesses, this means significantly reduced risk, consistent compliance, simplified audits and clearer oversight of how AI is actually being used.\nThis governance hub is paired with a set of agent spokes, dedicated environments where individual teams can build and deploy their agents. Each spoke is secure, consistent and fully connected to the centralised models, tools and services approved for the organisation. This structure gives businesses the best of both worlds: local autonomy for innovation, and global consistency for governance. A finance department can build its own agents at high speed, for example, without worrying about duplicating infrastructure or putting sensitive data at risk. Meanwhile, leadership teams retain a unified view of AI usage, costs and performance across the company.\nA key feature of Citadel is its reliance on a unified AI gateway. Instead of agents calling external AI services directly, every request routes through a single enterprise-standard endpoint. This allows the organisation to decide—centrally and intelligently—which models should be used, when they should be used, how they should be throttled and how their costs should be allocated. For businesses, this translates into predictable spending, easier budgeting, and the ability to optimise model usage without rewriting applications. Should a cheaper, faster or more accurate model emerge, it can be integrated once at the gateway and instantly made available to every agent.\nCitadel also provides detailed observability and compliance, enabling organisations to understand precisely how AI is contributing to business value. Rather than guessing how many tokens a department is consuming or which models are driving the highest costs, Citadel presents clear dashboards that break down usage by team, use case and model. This level of visibility supports better financial planning, more effective cost recovery between departments and stronger justification for further AI investment. It also provides the audit-ready insights needed for industries operating under regulatory scrutiny.\nYet Citadel is not only about control; it is equally concerned with accelerating AI development velocity. Building agents at scale requires a development process that is fast, repeatable and resistant to fragmentation. This is where spec-driven development and Spec2Cloud play a critical role. Instead of developers diving straight into code, they begin with a structured specification that outlines the agent’s architecture, responsibilities, edge cases, deployment model and compliance requirements. That specification is then transformed—often automatically—into working code, infrastructure and deployment pipelines using AI coding agents.\nFor businesses, the benefits are profound. Projects that previously took months can be delivered in days or weeks. Development quality becomes more consistent, because every agent begins with a robust template rather than a blank page. Knowledge becomes transferable, enabling new teams to onboard quickly and maintain existing systems without relying on tribal memory. And as organisations begin to accumulate hundreds of agent specifications, these documents evolve into a powerful internal asset: a reusable library of patterns that reflect the company’s operational and regulatory realities.\nThe result is a balanced ecosystem where innovation can flourish without sacrificing governance. Citadel allows organisations to experiment with new agentic ideas rapidly while ensuring that successful use cases can be promoted to production safely and reliably. It avoids the trap of building dozens of isolated pilots that never scale, instead providing a seamless path from concept to enterprise-grade deployment.\nPerhaps most importantly, Citadel positions businesses for the next major shift in AI: the move towards multi-agent systems. In the near future, it will not be unusual for one agent to collaborate with another—sometimes across business units, sometimes across organisations. Tools will become standardised through protocols such as MCP, allowing agents to access knowledge, perform actions and integrate with external systems through well-defined interfaces. Citadel’s architecture anticipates this future by creating a unified registry of models, tools and agents, enabling reuse, reducing duplication and ensuring compatibility as the organisation’s AI ecosystem grows more sophisticated.\nFor business leaders, the message is clear. If your organisation intends to operationalise AI at scale, you need an approach that supports both speed and safety. Citadel provides that foundation. It offers governance without friction, scalability without chaos, and innovation without risk. It creates an environment where AI is not an experimental add-on but a managed, strategic capability that strengthens every part of the business.\nAs companies increasingly look to AI to enhance productivity, streamline operations and improve customer experience, the organisations that succeed will be those that adopt a coherent governance platform early. Citadel is that platform—a blueprint for transforming AI from scattered experiments into a coordinated, high-performing engine of enterprise value.\n","date":"5 December 2025","externalUrl":null,"permalink":"/citadel-governance-hub-the-enterprise-blueprint-for-scaling-ai-safely-responsibly-and-efficiently/","section":"Articles","summary":"Businesses of every size are now moving far beyond early AI experimentation. What began with simple copilots and isolated proof-of-concepts has quickly evolved into a landscape where organisations expect to operate dozens—and soon thousands—of AI agents across their departments. These agents will collaborate with one another, call internal and external systems, interpret complex contexts and support increasingly critical business processes. As this shift accelerates, one question becomes unavoidable: how do we allow AI to scale without losing control, breaching compliance, duplicating effort or suffocating innovation?\n","title":"Citadel Governance Hub: The Enterprise Blueprint for Scaling AI Safely, Responsibly and Efficiently","type":"articles"},{"content":"Artificial Intelligence has rapidly evolved beyond simple productivity tools and into highly capable research assistants. One of the most promising innovations in Microsoft’s Copilot ecosystem is the Researcher Agent—a specialised AI agent designed to perform complex research tasks across a range of data sources and systems.\nIn this post, we explore what the Researcher Agent is, how it works, where it’s headed, and why it’s becoming an essential tool for knowledge workers and SMEs aiming to harness AI for serious productivity and strategic planning.\nWhat Is the Researcher Agent? The Researcher Agent is a purpose-built AI assistant that helps users conduct deep, structured research by accessing enterprise data, web content, and connected systems. Unlike standard AI chat interfaces, the Researcher Agent simulates human-style reasoning: asking clarifying questions, developing a plan of action, and reasoning step-by-step through a task.\nIt’s not designed for quick answers—it’s built for depth, making it ideal for generating reports, market analysis, competitive intelligence, and high-detail synthesis of large data sets.\nKey Features and Capabilities Multi-source Data Integration: The agent can draw from work data (emails, documents, notes), web sources, and even third-party systems—if your organisation has the right data connectors. Visible Chain of Thought: Users can see its internal reasoning and step-by-step logic. This transparency builds trust and allows you to follow how conclusions were reached. Clarifying Dialogue: Before it begins, it typically asks three or more contextual questions to fine-tune its understanding of your request. Rich Output: Expect comprehensive reports—often tens of thousands of words—complete with structured insights, metrics, and cited sources. Trade-offs: Depth vs Speed Unlike traditional Copilot tools designed for rapid interactions, the Researcher Agent takes time. Depending on the prompt and data volume, responses might take 10 to 60 minutes or more. It’s best used when you can “set it and forget it” while attending to other tasks.\nReal-World Use Cases Market Share Reports\nGenerate detailed industry analyses with cited sources, tables, and financial comparisons—tailored to your audience and timeframe. Customer Briefings\nPull together internal project data, emails, and meeting transcripts to prepare customer status reports or strategy briefs. Workshop and Presentation Prep\nRun multi-agent tasks to gather content for training decks, sales collateral, or weekly stakeholder updates. Competitive Intelligence\nBenchmark your company or products against market rivals using public and internal datasets. Using It in Microsoft 365 Today Currently, the Researcher Agent can be added via the “All Agents” section in Microsoft Copilot Chat. A new unified UI brings agents, history, and documents together on the left-side navigation panel, making it easier than ever to manage interactions.\n⚠️ Monthly Usage Limit: As of now, usage is capped at 25 conversations per user per month, so use it wisely.\nWhat’s Coming Next? Microsoft has ambitious plans for the Researcher Agent:\nWord Integration: Soon, it will live in the Word sidebar, helping you research directly from the text in your documents. Copilot Notebooks: This new workspace lets you combine documents, spreadsheets, and presentations into a single research area. Agent Collaboration: The agent can already communicate with other AI agents (e.g. Analyst) for orchestrated tasks, and future updates aim to improve this further. Graphical Outputs: New capabilities include generating visual data summaries—like charts and infographics—directly within its responses. Security \u0026amp; Trust: A Microsoft Advantage One of the key differentiators of the Researcher Agent is that it operates entirely within your Microsoft 365 tenant. Your data stays under your organisation’s control. It does not train Microsoft’s models and doesn’t leak outside your environment—making it suitable for sensitive business contexts.\nThis aligns with growing demand for AI tools that are secure by design, especially for organisations navigating compliance, data sovereignty, and risk mitigation.\nFinal Thoughts: A Research Revolution for the Enterprise The Researcher Agent represents a leap forward in enterprise AI. Its thoughtful reasoning, rich output, and secure data handling make it a game-changer for teams who need quality over speed.\nWhether you’re preparing for a board meeting, responding to a client, or mapping out market expansion, this tool helps you work like a strategist—with AI at your side.\n","date":"27 June 2025","externalUrl":null,"permalink":"/unlocking-the-power-of-microsofts-researcher-agent-a-deep-dive-into-intelligent-workflows/","section":"Articles","summary":"Artificial Intelligence has rapidly evolved beyond simple productivity tools and into highly capable research assistants. One of the most promising innovations in Microsoft’s Copilot ecosystem is the Researcher Agent—a specialised AI agent designed to perform complex research tasks across a range of data sources and systems.\n","title":"Unlocking the Power of Microsoft’s Researcher Agent: A Deep Dive into Intelligent Workflows","type":"articles"},{"content":"As organisations embrace AI to modernise operations, the architectural lens must now extend beyond infrastructure and applications to include how software teams interact with their tools. Enhancing the developer experience (DevEx) is becoming a vital strategic pillar, not only for productivity, but also for architectural consistency, security, and scalability.\nArchitectural Advantages of AI-Augmented Toolchains 1. Component Reusability AI tools such as GitHub Copilot assist developers in creating reusable components by suggesting functions, templates, and design patterns based on prior code. This shifts development away from bespoke, isolated implementations toward a library of modular services and utilities.\nFrom an architecture perspective:\nMicroservice and event-driven architectures benefit from consistent interface generation. AI helps enforce architectural patterns (e.g. Clean Architecture, Hexagonal Design) by nudging developers towards best practices. Component reusability simplifies maintenance, improves testability, and reduces duplication of logic across services. This reusability also supports DevSecOps pipelines by enabling pre-approved components that align with enterprise standards and policies.\n2. Security and Compliance by Design Embedding security into the software development life cycle is a core principle of modern architecture, often described as “shift-left security.” AI tools elevate this further by integrating static analysis, code scanning, and compliance checks directly within the developer workflow.\nKey architectural benefits include:\nEarly detection of vulnerabilities during coding or pull requests (via tools like GitHub Advanced Security). Automated security remediations and documentation, reducing dependency on manual reviews. Compliance monitoring across pipelines for standards like ISO 27001, SOC 2, and GDPR, improving audit readiness. Architects can use AI-driven security insights to evolve their threat modelling, reinforce zero trust principles, and ensure secure-by-default implementations.\n3. AI-Enhanced Knowledge and Documentation One of the biggest challenges in enterprise development is knowledge transfer—particularly when teams are distributed or there’s high turnover. AI tools can generate or augment documentation automatically and provide interactive explanations of systems in natural language.\nArchitecturally, this creates:\nSelf-service documentation layers that reduce dependency on subject matter experts. API guides, changelogs, and dependency diagrams that stay up to date without manual input. NLP-powered knowledge bases where developers can query internal systems (e.g., “How does the auth service validate tokens?”). This capability reduces friction in handovers and accelerates onboarding, helping architects maintain knowledge continuity across evolving teams and projects.\n4. Scalable Automation Across Environments AI plays a key role in automating across the entire SDLC, from provisioning infrastructure to deploying containerised workloads and validating post-deployment metrics. This automation extends from “hello world” applications to complex enterprise systems.\nArchitectural outcomes include:\nInfrastructure-as-Code (IaC) templates and Terraform modules enhanced by AI for rapid environment provisioning. Automated generation of test cases, deployment manifests, service health dashboards, and rollback procedures. Auto-remediation suggestions for misconfigured resources or failed deployments, helping close the loop between detection and resolution. AI helps enforce deployment consistency, enabling enterprise-grade scalability without proportional increases in DevOps overhead.\n5. Faster Onboarding and Reduced Cognitive Load AI copilots reduce the steep learning curve for new developers by serving as real-time assistants within IDEs like Visual Studio or JetBrains. They explain code, recommend next steps, and provide instant access to internal tooling and documentation.\nFor architects, this offers:\nReduced onboarding time for new hires or contract developers, minimising ramp-up periods. Lower context-switching overhead for experienced engineers, allowing more focus on complex architectural problems. Embedded guardrails that guide developers toward secure and standardised solutions without the need for constant human oversight. By codifying architectural decisions into the developer environment, AI reduces errors and enforces governance through enablement rather than control.\nFinal Thought: Embedding Architecture in the Development Experience These five pillars show how a well-designed, AI-augmented developer experience is not simply a productivity boost—it’s a core architectural enabler. It ensures consistency across projects, reduces risk, and increases the speed at which scalable, secure systems can be delivered.\nAs your organisation moves forward with AI, remember: it’s not just what you build, but how your teams are empowered to build it that defines long-term success.\n","date":"19 June 2025","externalUrl":null,"permalink":"/rethinking-technical-architecture-ai-driven-developer-experience-as-the-catalyst-for-scalable-innovation/","section":"Articles","summary":"As organisations embrace AI to modernise operations, the architectural lens must now extend beyond infrastructure and applications to include how software teams interact with their tools. Enhancing the developer experience (DevEx) is becoming a vital strategic pillar, not only for productivity, but also for architectural consistency, security, and scalability.\n","title":"Rethinking Technical Architecture: AI-Driven Developer Experience as the Catalyst for Scalable Innovation","type":"articles"},{"content":"The modern software landscape is evolving fast, and .NET developers need tools that keep up. Whether you’re spinning up a new microservice, building clean RESTful APIs, or wrangling Entity Framework migrations, wouldn’t it be ideal to have an assistant who knows .NET inside out?\nSay hello to Dot — your AI development partner, engineered for speed, precision, and deep domain expertise in the Microsoft ecosystem.\nWhat is Dot? Dot is a purpose-built AI assistant trained to think like a senior C# and .NET developer. Unlike generic coding tools, Dot is laser-focused on the Microsoft stack — including:\nASP.NET Core (Web API, Minimal API, MVC) Entity Framework Core (Code-First, InMemory, SQLite) .NET 6/7/8 SDKs Dependency Injection, Clean Architecture, and async/await patterns Azure-ready patterns and integration advice Dot helps developers of all levels scaffold new projects, refactor services, troubleshoot build errors, write idiomatic code, and navigate architectural trade-offs — all with the expertise you’d expect from a seasoned .NET engineer.\nWhy Use Dot? Here’s what makes Dot stand out in the growing crowd of AI tools:\nBuilt for .NET — Not Just “Code” Dot doesn’t just suggest code — it understands the .NET ecosystem. Whether you’re wiring up EF Core with migrations, implementing layered architecture, or building a repository pattern, Dot guides you the way a human mentor would.\nFast Project Scaffolding Need a working Web API with Swagger, DI, and SQLite? Dot can scaffold that in seconds. It creates the .csproj, wires up your Program.cs, and even configures EF Core and your data models — all in clean, production-ready C#.\nSafe by Design Dot defaults to safe, industry-aligned practices:\nNo raw SQL unless explicitly requested Proper use of async/await Secure DI patterns Testable, modular structure Clear separation of concerns Opinionated, in a Good Way Dot is not just a code suggester — it’s opinionated. It encourages best practices, prevents technical debt, and nudges you towards clean, maintainable architecture — especially helpful for solo developers or small teams without a dedicated architect.\nWhat Can Dot Help You With? Create ASP.NET Core projects from scratch Set up Entity Framework Core with migrations Scaffold APIs, services, and repositories Refactor legacy .NET Framework code to .NET 8 Mock or stub dependencies for testing Handle DI, logging, config, and health checks Review architecture decisions and recommend patterns Write unit and integration tests using xUnit or NUnit Example: Building a Minimal API in Seconds Imagine you want a quick web API for managing tasks using EF Core and SQLite.\nYou could ask:\n“Dot, create a .NET 8 Web API with a Todo model using EF Core and SQLite. Include a GET and POST endpoint, and scaffold the necessary DbContext.”\nDot will return:\nA new Program.cs file with minimal API setup A configured TodoDbContext A Todo model with attributes A *.csproj with all necessary dependencies Migration instructions and dotnet ef commands In under a minute, you’ve got a working API that’s clean, correct, and extendable.\nFinal Thoughts The goal of Dot isn’t to replace developers — it’s to empower them. Think of Dot as your always-on, never-tired teammate who knows the ins and outs of .NET.\nWhether you’re a junior just starting out or a senior juggling multiple services, Dot helps you move faster, code smarter, and stay aligned with modern development standards.\nReady to build with Dot? Get started by asking:\n“Dot, create a clean .NET 8 Web API with Swagger and a TasksController using EF Core.”\nAnd watch your ideas come to life — quickly, cleanly, and correctly.\nYou are Dot, an expert AI assistantDownload ","date":"20 May 2025","externalUrl":null,"permalink":"/meet-dot-your-expert-ai-assistant-for-c-and-net-development/","section":"Articles","summary":"The modern software landscape is evolving fast, and .NET developers need tools that keep up. Whether you’re spinning up a new microservice, building clean RESTful APIs, or wrangling Entity Framework migrations, wouldn’t it be ideal to have an assistant who knows .NET inside out?\n","title":"Meet Dot: Your Expert AI Assistant for C# and .NET Development","type":"articles"},{"content":"When building modern APIs that integrate with external systems, a common challenge is enabling efficient, scalable pagination — especially when the external system doesn’t support pagination natively. This post walks through a practical, production-ready solution using cursor-based pagination and Redis caching in a .NET Web API environment.\nThe Problem Let’s say your API needs to fetch large datasets (like order history, customer records, etc.) from an external third-party service. You might run into these issues:\nNo native pagination: The external system provides data as a whole without page support. Data volatility: Between client page requests, the dataset might change, leading to inconsistent results. High latency and cost: Fetching large datasets for each client request from the source is slow and expensive. Need for consistent paging: Clients expect a reliable and intuitive way to browse results. Traditional offset-based pagination (e.g., ?page=2\u0026amp;limit=10) can lead to skipped or repeated records when the underlying data changes. Cursor-based pagination, where the client receives a “bookmark” (cursor) for where to continue, offers a more stable solution.\nThe Strategy To overcome these challenges, our architecture uses caching and encoded cursors:\nInitial Fetch and Cache: When the client submits a query (e.g., customerId=123), we fetch the full result from the external API. The result set is cached in Redis using a key based on the query parameters. Serving Pages: The API slices the cached result based on a cursor and returns a portion of the dataset. A new cursor is returned with each response so the client can request the next set. Expiration: Redis cache keys are short-lived (e.g., 30 minutes), ensuring stale data is not reused too long. Stateless Clients: Clients don’t need to store or track offsets — the cursor encapsulates the position. Tools \u0026amp; Tech Stack Here’s what you’ll use:\n.NET Web API (C#): To expose REST endpoints. StackExchange.Redis: For high-performance Redis access. System.Text.Json: For efficient object serialization. Base64 Encoding: To safely encode the offset as a cursor. Building the Solution 1. Define Your Data Model We’ll use a simple OrderRecord model to represent each record.\npublic class OrderRecord { public string OrderId { get; set; } public DateTime CreatedAt { get; set; } public string CustomerId { get; set; } } 2. Cursor Utility Encodes/decodes page indexes so clients get a Base64 string instead of a raw integer.\npublic static class CursorHelper { public static string Encode(int index) =\u0026gt; Convert.ToBase64String(BitConverter.GetBytes(index)); public static int Decode(string cursor) { try { return BitConverter.ToInt32(Convert.FromBase64String(cursor), 0); } catch { return 0; } } }\n3. Redis Cache Service This abstracts Redis logic: caching the full dataset and reading it back.\nusing StackExchange.Redis; using System.Text.Json; public class RedisCacheService { private readonly IDatabase _redisDb;\npublic RedisCacheService(string connectionString) { var redis = ConnectionMultiplexer.Connect(connectionString); _redisDb = redis.GetDatabase(); } public async Task CacheResultsAsync(string key, List\u0026amp;amp;lt;OrderRecord\u0026amp;gt; records, TimeSpan expiry) { var json = JsonSerializer.Serialize(records); await _redisDb.StringSetAsync(key, json, expiry); } public async Task\u0026amp;amp;lt;List\u0026amp;amp;lt;OrderRecord\u0026amp;gt;\u0026amp;gt; GetCachedResultsAsync(string key) { var json = await _redisDb.StringGetAsync(key); return json.HasValue ? JsonSerializer.Deserialize\u0026amp;amp;lt;List\u0026amp;amp;lt;OrderRecord\u0026amp;gt;\u0026amp;gt;(json) : null; } }\n4. API Controller Your endpoint for cursor-based paging:\n[ApiController] [Route(\"api/[controller]\")] public class OrdersController : ControllerBase { private readonly RedisCacheService _cache; private readonly IExternalApiService _externalApi; // Abstracted external API call public OrdersController(RedisCacheService cache, IExternalApiService externalApi) { _cache = cache; _externalApi = externalApi; } [HttpGet] public async Task\u0026amp;amp;lt;IActionResult\u0026amp;gt; GetOrders([FromQuery] string customerId, [FromQuery] string cursor = null, [FromQuery] int pageSize = 50) { string cacheKey = $\u0026quot;orders:{customerId}\u0026quot;; var records = await _cache.GetCachedResultsAsync(cacheKey); if (records == null) { records = await _externalApi.FetchOrdersAsync(customerId); await _cache.CacheResultsAsync(cacheKey, records, TimeSpan.FromMinutes(30)); } int startIndex = string.IsNullOrEmpty(cursor) ? 0 : CursorHelper.Decode(cursor); var paged = records.Skip(startIndex).Take(pageSize).ToList(); string nextCursor = (startIndex + pageSize) \u0026amp;amp;lt; records.Count ? CursorHelper.Encode(startIndex + pageSize) : null; return Ok(new { data = paged, nextCursor = nextCursor }); } }\nExample Response { \"data\": [ { \"orderId\": \"1001\", \"createdAt\": \"2024-05-10T10:00:00Z\", \"customerId\": \"ABC123\" }, ... ], \"nextCursor\": \"NTA=\" // Base64 of offset 50 } The client can use nextCursor=NTA= in the next request to get the next page.\nBenefits of This Approach Performance: One-time call to external service; Redis serves repeated requests. Consistency: All paging is done over a snapshot, avoiding data drift. Scalability: Redis handles concurrent access well. Statelessness: The API doesn’t manage client state; cursors do. Resilience: Short TTLs help avoid stale or inconsistent results. Final Thoughts This is a highly reusable and scalable architecture for any API that needs to serve large datasets retrieved from an external system that lacks pagination support. By combining Redis caching with cursor-based pagination, you provide fast, stable, and user-friendly endpoints.\nYou can even extend this model to include:\nFiltering and sorting logic. Metadata responses like total counts. Multi-user cache invalidation. ","date":"18 May 2025","externalUrl":null,"permalink":"/building-cursor-based-pagination-with-redis-and-net-for-external-api-integrations/","section":"Articles","summary":"When building modern APIs that integrate with external systems, a common challenge is enabling efficient, scalable pagination — especially when the external system doesn’t support pagination natively. This post walks through a practical, production-ready solution using cursor-based pagination and Redis caching in a .NET Web API environment.\n","title":"Building Cursor-Based Pagination with Redis and .NET for External API Integrations","type":"articles"},{"content":"In my original Polly article, I introduced Polly as a robust resilience framework for handling transient faults and service failures. At the time, Polly was entirely community-driven and required manual configuration within each application. Fast forward five years, and Microsoft has officially embraced the concepts introduced by Polly, incorporating them directly into the .NET framework with a suite of first-party resilience libraries.\nThis article explores how fault tolerance has evolved in .NET, highlighting the new Microsoft.Extensions.Resilience and Microsoft.Extensions.Http.Resilience libraries. These packages allow developers to configure and apply resilience strategies like retry policies, circuit breakers, and timeouts using cleaner, more integrated code.\nWhat Has Changed? Historically, .NET developers had to install Polly via NuGet, manually define resilience strategies, and wire them into their HTTP clients and service calls. This approach, while powerful, required a deeper understanding of Polly’s API and how to properly manage dependencies and middleware in an application.\nWith .NET 8, Microsoft introduced Microsoft.Extensions.Resilience and related packages. These libraries:\nIntegrate directly with the .NET dependency injection system. Offer predefined, composable strategies out-of-the-box. Reduce configuration overhead. Enhance observability by plugging into diagnostics and OpenTelemetry. Simplify testing and monitoring with a consistent programming model. Microsoft has essentially brought resilience into the core of .NET, giving developers native tooling to build robust, production-grade systems.\nSetting Up the Resilience Framework To get started with the new resilience capabilities in .NET 8, you’ll need to install the following packages:\ndotnet add package Microsoft.Extensions.Resilience dotnet add package Microsoft.Extensions.Http.Resilience These packages allow you to add prebuilt resilience handlers to your HTTP clients and define custom policies for use elsewhere in your application. The integration with IHttpClientFactory means you can set up these handlers declaratively in your Startup.cs or program configuration.\nA Simple Example with HttpClient Let’s look at how easy it is to configure a resilient HTTP client. Below is an example that creates a named client with a standard resilience pipeline:\nbuilder.Services .AddHttpClient(\"resilient-client\") .AddStandardResilienceHandler(options =\u0026gt; { options.TotalRequestTimeout = TimeSpan.FromSeconds(10); options.Retry.MaxRetryAttempts = 3; options.CircuitBreaker.FailureThreshold = 0.5; options.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(30); }); This setup gives you retry, timeout, and circuit breaker policies configured with sensible defaults. You can then inject this client into your services:\npublic class MyService { private readonly HttpClient _httpClient; public MyService(IHttpClientFactory httpClientFactory) { _httpClient = httpClientFactory.CreateClient(\u0026quot;resilient-client\u0026quot;); } public async Task\u0026amp;amp;lt;string\u0026amp;gt; GetDataAsync() { var response = await _httpClient.GetAsync(\u0026quot;https://example.com/api/data\u0026quot;); return await response.Content.ReadAsStringAsync(); } }\nThis level of simplicity allows developers to quickly adopt best practices without needing to dive deeply into Polly internals.\nCustomising the Pipeline While the standard handler is excellent for most scenarios, Microsoft also allows complete control by defining a custom pipeline. This is useful when you need to adjust parameters for retry timing, circuit breaker thresholds, or other strategies.\nbuilder.Services .AddResiliencePipelineBuilder(\"custom-pipeline\") .AddTimeout(TimeSpan.FromSeconds(5)) .AddRetry(new RetryStrategyOptions { MaxRetryAttempts = 3, Delay = TimeSpan.FromSeconds(2), BackoffType = DelayBackoffType.Exponential }) .AddCircuitBreaker(new CircuitBreakerStrategyOptions { FailureThreshold = 0.25, SamplingDuration = TimeSpan.FromSeconds(20), MinimumThroughput = 5, BreakDuration = TimeSpan.FromSeconds(30) }); You can then bind this custom pipeline to an HTTP client:\nbuilder.Services .AddHttpClient(\"custom-client\") .AddResilienceHandler(\"custom-pipeline\"); The flexibility here means you can tailor fault tolerance to the unique behaviours and requirements of each endpoint.\nAdding Fallback Logic Fallback logic is used when a request fails and you want to return a default value or alternate result. This is particularly useful in microservice or distributed systems where availability is more critical than accuracy in some cases.\n.AddFallback(new FallbackStrategyOptions\u0026amp;lt;HttpResponseMessage\u0026gt; { ShouldHandle = args =\u0026gt; ValueTask.FromResult( args.Outcome.Result?.StatusCode == HttpStatusCode.InternalServerError), FallbackAction = args =\u0026amp;gt; ValueTask.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(\u0026quot;{ \\\u0026quot;message\\\u0026quot;: \\\u0026quot;Default response\\\u0026quot; }\u0026quot;) }) });\nIn this example, if the external API returns a 500 error, the fallback will trigger and return a default JSON payload.\nBulkhead Isolation (Back Again, But Better) Bulkhead isolation prevents one failing component from exhausting system resources and affecting others. It limits the number of concurrent actions and optionally queues overflow requests.\n.AddConcurrencyLimiter(new ConcurrencyLimiterStrategyOptions { PermitLimit = 2, // Max concurrent executions QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueLimit = 4 }); This is especially important in high-traffic applications or when calling slow or unreliable external services.\nWhen all slots and queues are full, the framework throws a BulkheadRejectedException, allowing you to log or trigger alerts appropriately.\nMonitoring and Observability A major advantage of Microsoft’s approach is deep integration with observability tools. You can use diagnostic listeners or OpenTelemetry to track resilience behaviour.\nbuilder.Services.AddOpenTelemetry() .WithTracing(tracerBuilder =\u0026gt; tracerBuilder .AddHttpClientInstrumentation() .AddAspNetCoreInstrumentation() ); This enables tracing of retries, timeouts, and circuit breaker activity in tools like Jaeger, Zipkin, or Azure Monitor.\nSummary Microsoft’s new resilience framework in .NET 8 significantly improves how we manage fault tolerance. By building upon Polly and deeply integrating it into the .NET ecosystem, Microsoft makes resilience strategies easier to configure, maintain, and observe.\nIf you previously implemented Polly manually, the transition to Microsoft’s official packages can reduce complexity and align your application with future .NET best practices.\nReferences Polly GitHub Microsoft Docs on Resilience Standard Resilience Pipeline Chaos Engineering in .NET ","date":"6 May 2025","externalUrl":null,"permalink":"/advanced-fault-tolerance-in-net-8-using-microsofts-resilience-framework/","section":"Articles","summary":"In my original Polly article, I introduced Polly as a robust resilience framework for handling transient faults and service failures. At the time, Polly was entirely community-driven and required manual configuration within each application. Fast forward five years, and Microsoft has officially embraced the concepts introduced by Polly, incorporating them directly into the .NET framework with a suite of first-party resilience libraries.\n","title":"Advanced Fault Tolerance in .NET 8 Using Microsoft’s Resilience Framework","type":"articles"},{"content":"","date":"6 May 2025","externalUrl":null,"permalink":"/categories/design-patterns/","section":"Categories","summary":"","title":"Design Patterns","type":"categories"},{"content":"","date":"6 May 2025","externalUrl":null,"permalink":"/categories/programming-principles/","section":"Categories","summary":"","title":"Programming Principles","type":"categories"},{"content":"","date":"16 April 2025","externalUrl":null,"permalink":"/categories/api/","section":"Categories","summary":"","title":"API","type":"categories"},{"content":"In the world of modern software systems, APIs are the gateways through which applications access and interact with data. But when these APIs expose large datasets—like financial transactions, audit trails, or customer activity—they can easily become bottlenecks or even points of failure if not designed with care.\nWhether you’re building public APIs for external consumers or internal services powering enterprise dashboards, managing large data queries is a challenge that demands attention. In this article, we’ll explore five well-established API design patterns that can help mitigate risks, improve performance, and enhance the overall developer and user experience.\n1. Limit the Date Range for Queries One of the most common performance traps in data-heavy APIs is allowing unrestricted date range queries. Users may accidentally (or intentionally) request years’ worth of records, potentially triggering massive database scans, long response times, or timeouts.\nBest Practice:\nEnforce a maximum range between fromDate and toDate. For example, limit requests to 30 or 60 days, and return a validation error if the threshold is exceeded.\nWhy it matters:\nPrevents performance degradation Encourages more focused, relevant queries Reduces strain on infrastructure Optional enhancement:\nIf appropriate, truncate wide date ranges automatically and return a message in the response indicating that limits were applied.\n2. Use Pagination for All List Endpoints Large datasets should never be returned in a single API response. Pagination ensures that responses are manageable in size, improves user interface performance, and avoids hitting size or memory limits in HTTP clients.\nCommon parameters:\npageNumber – the page of results to retrieve pageSize – how many results to include per page Best Practice:\nInclude totalRecords in the response body to help clients calculate the number of pages and design appropriate navigation.\nWhy it matters:\nEnhances API scalability Supports better user experience in paginated views Helps protect bandwidth and avoid dropped connections 3. Apply Default Filters for Safer Defaults Sometimes, users may forget to provide query parameters altogether. If your API defaults to returning everything, it can be problematic.\nBest Practice:\nApply sensible default filters—like returning only records from the last 7 or 30 days—and clearly document this behaviour.\nWhy it matters:\nProvides a safeguard against inefficient queries Delivers faster, more relevant responses out of the box Encourages adoption by being helpful and forgiving Tip:\nReturn a notice in the metadata to inform users that a default filter was applied, especially in developer-facing APIs.\n4. Implement Rate Limiting to Control Load APIs are often shared across teams, platforms, or even third-party clients. To avoid abuse and overuse, especially when heavy queries are allowed, rate limiting is essential.\nBest Practice:\nUse API gateways or traffic management tools to enforce limits on:\nRequests per minute Concurrent connections Data volume thresholds Why it matters:\nPrevents service outages due to spike loads Ensures fair use of shared infrastructure Discourages inefficient polling or misuse Pro tip:\nImplement tiered limits—higher for internal or premium clients, tighter for public or anonymous access.\n5. Enable Caching for Repeat Access If your users frequently request similar datasets—such as invoices from the same month or a list of top-selling products—caching can massively improve performance.\nTwo useful caching strategies:\nResponse caching – Store the result of entire GET requests for common filters. Entity caching – Keep frequently accessed items (like invoice headers or metadata) in memory or a cache store. Why it matters:\nDecreases backend load Improves latency Delivers a better user experience with instant responses Putting It All Together These five patterns work best in combination. A mature API might:\nReject or truncate queries over 30 days Return no more than 50 records per page Default to returning the last 7 days if no filter is given Throttle access at 100 requests per minute Cache invoice details for 5 minutes to serve duplicate queries Together, they form a robust strategy for controlling the size and impact of large queries in your API ecosystem.\nFinal Thoughts As data volumes grow and API usage expands, thoughtful design becomes critical. Building scalable, safe, and performant APIs requires both a developer mindset and a user-centric approach.\nThese patterns—date range limits, pagination, default filters, rate limiting, and caching—are foundational to any large-scale API that deals with potentially heavy data.\nNext step:\nIf you’re designing APIs in this space, consider baking these into your design reviews, documentation, and performance testing scenarios. And if your back-end system (like an ERP or legacy service) can’t enforce these limits directly, your integration or middleware layer can—and should.\n","date":"16 April 2025","externalUrl":null,"permalink":"/designing-resilient-apis-preventing-large-data-downloads-with-best-practice-patterns/","section":"Articles","summary":"In the world of modern software systems, APIs are the gateways through which applications access and interact with data. But when these APIs expose large datasets—like financial transactions, audit trails, or customer activity—they can easily become bottlenecks or even points of failure if not designed with care.\n","title":"Designing Resilient APIs: Patterns to Manage Large Data Queries","type":"articles"},{"content":"Artificial Intelligence (AI) is no longer the stuff of science fiction. From automating emails to analysing business trends, AI agents are already helping organisations save time, reduce costs, and make better decisions. But with great power comes great responsibility—and that’s where governance comes into play.\nIn today’s rapidly evolving digital landscape, many businesses—especially small and medium-sized enterprises (SMEs)—are racing to adopt AI without first asking a critical question: Who’s in control?\nIf your organisation is experimenting with AI, you need more than just a clever tool. You need a framework that ensures AI is used safely, effectively, and ethically.\nBeyond the Hype: What AI Governance Actually Means Governance, in the context of AI, isn’t about stifling innovation. It’s about making sure the right checks and balances are in place to prevent costly mistakes.\nThink of it like building a motorway: the goal is to keep traffic flowing, but you still need road signs, speed limits, and the occasional roundabout. Good AI governance puts up just enough guardrails to keep everything moving in the right direction—safely.\nNot All AI is Created Equal Some AI tools are incredibly simple—a chatbot that helps schedule meetings, or a tool that suggests edits to a document. Others are more complex, like automated systems that manage finances, handle customer data, or even make decisions on behalf of the business.\nGovernance should reflect the level of risk. For instance:\nLow-risk AI (e.g. tools used by individuals) may need only basic oversight. Medium-risk AI (e.g. shared team tools) might require sign-off from a manager or IT. High-risk AI (e.g. customer-facing or sensitive data tools) should go through full compliance, security, and operational review. In short, the more an AI tool touches critical systems or customer data, the tighter your governance should be.\nThe Three Pillars of Smart AI Governance Process\nAI projects should go through the same rigour as any IT initiative. This means clear planning, testing, and deployment procedures—ideally integrated into your existing project or change management processes. Platform\nUse technical controls to manage access and monitor usage. This includes role-based permissions, environment restrictions, and data loss prevention tools. People\nAI is only as smart as the people using it. Invest in training, foster communities of practice, and empower your staff to use AI responsibly. Everyone should understand that AI is there to assist, not replace, their judgement. Lessons from the Past: Don’t Repeat the Mistakes of Power Tools Many organisations that adopted automation platforms in the past learned some tough lessons: without support and structure, well-meaning staff can end up creating isolated tools, duplicated effort, and even security risks.\nAI is no different. If you don’t put governance in place from the start, you could find yourself with dozens of unsupported, undocumented, and potentially risky tools scattered across the business.\nShould You Build, Buy, or Adapt? Before developing a new AI solution, ask yourself: Do we really need to build this from scratch?\nOften, the answer is no. You may already have systems in place—like your CRM or service desk—that can be extended with AI functionality. Building your own might seem appealing, but it’s usually more costly and time-consuming. Choose the right tool for the job, not the flashiest one.\nCost and Value: Keeping AI Spend Under Control One of the biggest hidden risks with AI is cost. Some tools are pay-as-you-go, while others require upfront licences or monthly subscriptions. As usage grows, costs can spiral—especially if you’re not monitoring adoption and usage properly.\nA good governance strategy includes clear cost forecasting and budgeting to ensure you get value from your investment.\nFinal Thoughts: Getting Governance Right AI has the potential to transform how we work—but only if it’s handled with care. A thoughtful governance model doesn’t just protect your business; it enables it.\nBy aligning controls to the complexity and risk of each AI use case, and by supporting your people with training and clarity, you can safely explore the possibilities AI has to offer.\nSo, whether you’re an SME just starting your AI journey or a larger organisation ready to scale up, one thing is certain: it’s time to get your governance in order—before the machines start making the rules.\nNeed help getting started?\nConsider appointing an AI champion in your business or partnering with a consultant who understands both the technology and the human side of change. The future of work isn’t just automated—it’s accountable.\n","date":"28 March 2025","externalUrl":null,"permalink":"/taming-the-machines-why-ai-governance-matters-more-than-ever/","section":"Articles","summary":"Artificial Intelligence (AI) is no longer the stuff of science fiction. From automating emails to analysing business trends, AI agents are already helping organisations save time, reduce costs, and make better decisions. But with great power comes great responsibility—and that’s where governance comes into play.\n","title":"Taming the Machines: Why AI Governance Matters More Than Ever","type":"articles"},{"content":"There’s no denying it: artificial intelligence has become an integral part of the way we work. Once the subject of science fiction, it now quietly supports us, helping with everything from writing reports and drafting emails to summarising meetings and finding answers at lightning speed. Yet, as with every great tool in history, the magic of AI lies not just in what it can do, but in how we choose to use it.\nIn recent months, the conversation around responsible AI use has gained momentum. It’s easy to be swept up in the convenience and creativity AI offers, but the real challenge lies in ensuring that, in our enthusiasm, we do not forget the principles that protect privacy, uphold trust, and respect the world around us.\nOne of the first areas where responsibility must shine through is in how we engage with AI itself. The prompts we give matter. They shape the output, tone and integrity of the content we receive. Asking AI to evaluate someone’s emotions, mimic the style of a well-known author, or generate content that could be discriminatory is not just a poor use of the technology — it undermines the ethical standards we all rely on. We must prompt with care, knowing that the way we ask shapes the answers we get.\nSimilarly, while AI can be a helpful companion in meetings, there are times when it simply doesn’t belong. Sensitive conversations about health, legal matters, or personal issues demand privacy and trust, not digital recording or analysis. Even small, one-on-one conversations, unless agreed upon by senior leaders, should remain AI-free zones. Knowing when to invite AI into the room — and when to leave it outside — is part of using this technology with wisdom.\nAs our reliance on AI grows, so too does the need to draw clear boundaries between our professional and personal worlds. Storing private data alongside work content risks unintended exposure, and the lines can blur all too easily if we are not careful. Keeping personal information in clearly defined spaces and making sure that AI tools only access approved work areas is not just a best practice; it’s essential.\nWhen it comes to client work, responsibility becomes even more critical. Before using AI to generate or process anything on behalf of a client, we need to ensure that it’s not only allowed but welcomed. Some contracts carry restrictions, and data security obligations can be complex. It’s far better to pause and ask for clarification than to risk breaching trust or legal agreements.\nOnce content is created, the job isn’t done. Good stewardship means protecting what has been generated. Applying sensitivity labels and double-checking who has access keeps information safe and secure. It’s all too easy to assume that once a document is written, it’s ready to be shared — but a moment spent reviewing permissions can prevent countless headaches later on.\nAnd while live demonstrations of AI tools can be impressive, they’re not without risk. Demonstrating AI on untested or confidential material could lead to embarrassing slip-ups or even breaches of sensitive information. Preparation and careful review should always be part of the process before any showcase.\nThe accuracy of AI outputs is another area where human oversight must remain front and centre. AI is an incredible tool, but it isn’t infallible. Errors, bias, or unintended messaging can slip through unnoticed unless we stay vigilant. Reviewing AI-generated content with a critical eye and a sense of accountability is non-negotiable.\nFinally, one of the simplest but most powerful principles is transparency. People have a right to know when AI is being used — whether in meetings, emails, or content creation. Labelling AI-generated work and giving others the chance to opt out of AI-assisted interactions builds trust and prevents misunderstandings. It’s not just about compliance; it’s about respect.\nResponsible AI use isn’t about slowing down innovation or placing limits on creativity. It’s about making sure that the tools we use enhance our work in ways that are safe, ethical, and considerate. AI has the power to transform the way we live and work — but only if we handle it with care. The future is bright, but it’s also in our hands.\nIf you’re unsure about best practices or want help establishing responsible AI habits in your team, support is available. After all, using AI responsibly isn’t just good practice. It’s how we build a future that’s smart, secure and trusted by all.\n","date":"25 March 2025","externalUrl":null,"permalink":"/the-art-of-using-ai-responsibly/","section":"Articles","summary":"There’s no denying it: artificial intelligence has become an integral part of the way we work. Once the subject of science fiction, it now quietly supports us, helping with everything from writing reports and drafting emails to summarising meetings and finding answers at lightning speed. Yet, as with every great tool in history, the magic of AI lies not just in what it can do, but in how we choose to use it.\n","title":"The Art of Using AI Responsibly","type":"articles"},{"content":"Introduction DeepSeek has been making waves in the AI community, with its recent R1 model release being described as a potential ‘Sputnik moment’ by influential venture capitalist Marc Andreessen. But how much of the hype is justified, and is DeepSeek truly a game-changer in the AI landscape?\nBackground: What is DeepSeek? Founded in late 2023 by Liang Wenfeng, DeepSeek is a Chinese AI company with roots in both hedge funds and AI research. With a team of approximately 200 employees, the company has managed to develop and release its first major model, DeepSeek-R1, in record time.\nKey Facts About DeepSeek-R1: Released on 20th January 2025 Developed in just two months with a budget of less than $6 million Features 671 billion parameters and a 128K context window Nearly matches OpenAI’s o1 model in artificial analysis quality but lags in speed Forced to use Nvidia’s less-powerful H800s due to US export restrictions Licensed under the MIT License, allowing full commercial use and modifications Designed as an ‘expert system’ rather than a monolithic AI The Expert System Approach: A Smarter AI Architecture? One of DeepSeek’s most intriguing innovations is its approach to AI architecture. Unlike traditional models that attempt to load all their parameters at once, DeepSeek employs a more modular and memory-efficient strategy:\nInstead of running a single model trained to perform every task, DeepSeek-R1 uses a specialised expert system. Only 37 billion parameters are active at any given time, significantly reducing memory usage. This is akin to assembling a team of specialists who are only activated when their expertise is required, rather than keeping all team members engaged simultaneously. This model has clear advantages:\nEfficiency: Lower hardware requirements mean DeepSeek could be more accessible for enterprise deployment. Scalability: The modular expert approach allows for better specialisation and adaptability. Potential Cost Savings: Reduced computational load could lower operational costs over time. Performance \u0026amp; Limitations While DeepSeek-R1 is impressive in its ability to nearly match OpenAI’s o1 model in analysis quality, its performance is not without drawbacks:\nSpeed Issues: The model is not as fast as some of its Western competitors, which could be a limiting factor in real-time applications. Hardware Limitations: Due to US export restrictions, DeepSeek was forced to train using Nvidia’s H800s rather than more powerful alternatives. While this led to some novel training efficiencies, it may also mean performance ceilings are lower than those of competitors with access to better hardware. Market Positioning: Although DeepSeek has open-sourced R1, the company still lacks the ecosystem and widespread adoption of models from OpenAI or Anthropic. Whether they can attract a robust developer community remains to be seen. Open-Source Potential: Disruptive or Overblown? DeepSeek has taken the bold step of open-sourcing its model under the MIT License. This allows for commercial use, modification, and even training of derivative models. The implications of this include:\nMore Competitive Open-Source AI: Companies and researchers can use DeepSeek-R1 to build their own AI models without restrictive licensing. Potentially Faster AI Development in China: With US AI restrictions in place, China’s AI industry may use DeepSeek as a springboard to accelerate domestic development. Risk of Fragmentation: While open-source AI is generally positive, there is a risk of fragmentation as companies modify and fine-tune the model in different ways. Conclusion: Big News, but Not an AI Revolution (Yet) DeepSeek-R1 is undoubtedly a major development, but calling it a ‘Sputnik moment’ may be premature. While it presents exciting innovations, particularly with its expert system approach, it still faces challenges in speed, hardware limitations, and market penetration. However, the open-source licensing and cost-efficient architecture make it a serious contender in the AI race.\nThe coming months will determine whether DeepSeek can build on this foundation and compete with AI giants like OpenAI and Google. If they can refine their models, improve speed, and gain broader industry adoption, DeepSeek could be a major player in the future of AI.\n","date":"31 January 2025","externalUrl":null,"permalink":"/deepseek-big-news-but-overhyped/","section":"Articles","summary":"Introduction DeepSeek has been making waves in the AI community, with its recent R1 model release being described as a potential ‘Sputnik moment’ by influential venture capitalist Marc Andreessen. But how much of the hype is justified, and is DeepSeek truly a game-changer in the AI landscape?\n","title":"DeepSeek: Big News, But Overhyped?","type":"articles"},{"content":"In today’s fast-paced tech landscape, the fusion of AI and DevOps is revolutionising the developer experience. As businesses strive to innovate continuously, software development teams have become indispensable. Yet, this pivotal role has also led to increased workloads and the necessity for new skills, especially with the convergence of coding, security, and IT management. We delves into how AI-enabled tools and DevOps can enhance developer satisfaction, productivity, and creativity, reducing burnout and fostering a more engaging work environment.\nWhy 92% of Developers Are Using AI Coding Tools A recent GitHub survey highlighted that 92% of developers are already leveraging AI coding tools, with 67% using them both professionally and personally. This widespread adoption is driven not just by hype but by tangible benefits such as improved code quality, faster outputs, and fewer production-level incidents. Despite this, many organisations still measure developer productivity by the volume of code produced, a metric that many developers find outdated. They advocate for new measures that prioritise code quality and security, which ultimately drive both job satisfaction and better business outcomes.\nEnhancing Creativity, Problem-Solving, and Collaboration Developers’ enthusiasm for AI coding tools stems from their ability to facilitate creative problem-solving and exploration of diverse coding styles. The GitHub survey found that 80% of developers believe AI tools will enhance team collaboration, with tools like GitHub Copilot helping to standardise coding practices across teams. This standardisation removes barriers to collaboration, especially among developers with different backgrounds.\nIncreasing Satisfaction and Reducing Burnout AI tools also contribute significantly to reducing non-critical mental effort, with 41% of developers agreeing that these tools help avoid burnout. Managers play a crucial role here by reallocating time saved on coding to focus on quality, security, and innovation. Engaging work leads to a 30% increase in productivity, highlighting the importance of a stimulating work environment.\nSecuring Code from the Start Security is a critical aspect of development that AI tools can significantly enhance. GitHub Copilot, for example, helps block insecure coding patterns and proactively identifies vulnerabilities during development. Incorporating security features such as code scanning, secret scanning, and dependency scanning into the development workflow is essential, especially for teams that perform most security testing in later stages.\nFocusing on Deep Work with AI and DevOps Deep work, a concept popularised by Cal Newport, is essential for developers who need to solve complex problems and create innovative solutions. However, it’s often disrupted by distractions and inefficiencies. DevOps presents an opportunity to foster deep work by improving the quality and security of applications and encouraging collaboration between traditionally siloed areas like software development, IT operations, quality assurance, and security. This holistic approach reduces repetitive tasks, allowing developers to focus more on creative aspects of their work.\nAdopting DevOps Adopting DevOps involves understanding its core principles, promoting a collaborative culture, selecting the right tools, automating processes, and ensuring security throughout the development lifecycle. Implementing continuous integration and continuous delivery (CI/CD) pipelines helps catch issues early and makes deployments more predictable. Continuous monitoring and optimisation of DevOps processes are also vital for sustained improvement.\nIntegrating AI-Enabled Tools into DevOps Incorporating tools like Microsoft and GitHub products into your DevOps practice can significantly enhance the developer experience. These tools provide the tech stack and processes needed to improve application quality, resilience, security, and impact. For instance, Azure AI services, GitHub Copilot, and Azure DevOps offer comprehensive solutions that support various languages and frameworks, enabling developers to work more efficiently and securely.\nPlanning Your Developer Productivity Solution The integration of GitHub Copilot, Azure DevOps, and Visual Studio enriches the developer experience by making the software development process more intuitive, efficient, and enjoyable. This combination enhances individual capabilities and creates a cohesive environment where developers can thrive. By streamlining workflows and fostering innovation, developers become more satisfied and engaged, leading to higher productivity, improved business outcomes, and increased retention.\nNext Steps To get started, explore how to use GitHub and Azure together, take the Introduction to GitHub Copilot learning module, and calculate your organisation’s Developer Velocity score to get guidance on boosting business performance. By embracing AI and DevOps, you can create a more productive, creative, and satisfying developer experience that drives your organisation forward.\nThis is a good reference to further your knowledge\nRedefining-the-Developer-Experience-WIth-AIDownload ","date":"5 June 2024","externalUrl":null,"permalink":"/redefining-the-developer-experience-with-ai-and-devops/","section":"Articles","summary":"In today’s fast-paced tech landscape, the fusion of AI and DevOps is revolutionising the developer experience. As businesses strive to innovate continuously, software development teams have become indispensable. Yet, this pivotal role has also led to increased workloads and the necessity for new skills, especially with the convergence of coding, security, and IT management. We delves into how AI-enabled tools and DevOps can enhance developer satisfaction, productivity, and creativity, reducing burnout and fostering a more engaging work environment.\n","title":"Redefining the Developer Experience with AI and DevOps","type":"articles"},{"content":"","date":"7 May 2024","externalUrl":null,"permalink":"/categories/azure/","section":"Categories","summary":"","title":"Azure","type":"categories"},{"content":"In the constantly evolving landscape of cloud computing, security remains a paramount concern, especially for platforms as extensively utilised as Microsoft Azure. This blog delves into the importance of implementing robust security measures, illustrated through a case study on structured automation and controlled provisioning in a secure-by-design environment.\nThe Need for Enhanced Security in Cloud Environments As organisations migrate more of their critical operations and sensitive data to the cloud, the complexity of managing these resources escalates. The primary challenge lies not just in handling the sheer volume of data but also in ensuring that all transactions and storage are secure from unauthorised access and breaches. Here, the concepts of structured automation and controlled provisioning come into sharp focus.\nStructured Automation Structured automation refers to the systematic approach to deploying resources, applications, and services in the cloud. By automating these processes, organisations can minimise human error, a significant factor in security breaches. Automation ensures that every step adheres to predefined procedures, reducing the likelihood of misconfigurations and vulnerabilities that hackers might exploit.\nControlled Provisioning Controlled provisioning involves setting strict protocols and permissions for resource allocation within the cloud environment. This practice ensures that resources are not only provisioned through an automated pipeline but also comply with the organisation’s security policies and standards. Controlled provisioning helps maintain a clear trail of resource deployment and usage, crucial for auditing and compliance.\nImplementing Best Practices in Azure To effectively implement structured automation and controlled provisioning, several best practices can be followed:\nRole-Based Access Control (RBAC): Clearly defining roles and responsibilities within the Azure environment ensures that individuals only have access to the resources necessary for their work. This minimises potential internal threats and data leaks. Multi-Factor Authentication (MFA): MFA adds an extra layer of security by requiring two or more verification methods to gain access to Azure resources, which significantly reduces the risk of unauthorised access. Regular Security Audits: Conducting periodic audits helps identify and rectify security gaps in the cloud infrastructure. These audits should review compliance with established security policies and the effectiveness of implemented controls. Incident Response Plan: Having a robust incident response plan ensures that any security breach is quickly contained and addressed. This plan should outline clear steps for mitigating damage, investigating breaches, and restoring security. Adherence to Security Frameworks: Utilising established security frameworks, such as those provided by NIST or the ISO 27000 series, can guide the setup and maintenance of security measures in Azure. Case Study Insights A recent project involved deploying an advanced cloud resource management tool designed to automate provisioning within a secure Azure environment. This tool, structured to automate deployment and ensure rigorous access controls, exemplifies how automation and provisioning can coexist with heightened security measures. The deployment was structured to inherit Azure’s security controls, ensuring that any resource provisioned through this tool adhered to the highest security standards.\nConclusion The integration of structured automation and controlled provisioning within Azure not only streamlines operations but significantly enhances security. By automating processes and controlling resource allocation, organisations can protect themselves against both external attacks and internal vulnerabilities. As cloud technologies continue to develop, maintaining strict security protocols will remain essential in safeguarding valuable data and systems in the Azure cloud.\nThis approach to cloud security, focusing on automation and strict provisioning controls, demonstrates a proactive stance in cloud management, ensuring that security is not a byproduct but a fundamental aspect of the operational framework.\n","date":"7 May 2024","externalUrl":null,"permalink":"/enhancing-azure-security-through-structured-automation-and-controlled-provisioning/","section":"Articles","summary":"In the constantly evolving landscape of cloud computing, security remains a paramount concern, especially for platforms as extensively utilised as Microsoft Azure. This blog delves into the importance of implementing robust security measures, illustrated through a case study on structured automation and controlled provisioning in a secure-by-design environment.\n","title":"Enhancing Azure Security Through Structured Automation and Controlled Provisioning","type":"articles"},{"content":"","date":"7 May 2024","externalUrl":null,"permalink":"/categories/security/","section":"Categories","summary":"","title":"Security","type":"categories"},{"content":"Generative Artificial Intelligence (AI) represents one of the most significant technological advancements, offering capabilities that blur the lines between content generated by machines and humans. As we navigate this new frontier, it’s paramount that we guide this innovation responsibly. Emphasising the principles of responsibility and privacy, this guide provides a comprehensive roadmap for developing AI solutions that are not only advanced but also ethical and responsible.\nCore Principles of Responsible AI Development\nA strong emphasis is placed on the principles of responsibility and privacy, which are ingrained at the very foundation of every service and product. In the domain of generative AI, where the innovation potential is as immense as the potential for risk, adopting a responsible approach is critical. This involves a deliberate, structured process to ensure that AI technologies are developed and deployed in a manner that upholds ethical standards and societal values.\nA Structured Approach to Ethical AI\nOutlined below is a meticulous four-stage process designed to navigate the complexities of generative AI development responsibly:\nIdentifying Potential Harms: The first step in the journey involves a critical evaluation to identify potential harms that could emerge from the AI solution. This proactive step is crucial for understanding the spectrum of adverse impacts, including the generation of offensive or discriminatory content, the propagation of factual inaccuracies, or the encouragement of illegal behaviours. Utilising tools such as the Responsible AI Impact Assessment Guide aids in this comprehensive review, ensuring that potential risks are not only identified but also thoroughly documented and assessed. Measuring Identified Harms: With potential harms identified, the subsequent phase involves measuring their presence within the AI solution’s outputs. This critical evaluation step requires deploying diverse input prompts to test the system, followed by a rigorous analysis of the outputs against predefined criteria. This process establishes a baseline of potential harm, enabling developers to quantify and track the effectiveness of mitigation efforts as the solution evolves. Mitigating Harms: Addressing the identified risks necessitates a layered mitigation strategy. This encompasses several layers: The model layer focuses on the selection or fine-tuning of the AI model to minimise risks. The safety system layer includes platform-level configurations such as content filters to enhance safety. The metafront and grounding layer refine input prompts to guide the AI towards generating relevant, non-harmful outputs. The user experience layer involves designing the application interface and documentation to mitigate potential harms and communicate transparently about the system’s capabilities and limitations. Each layer presents unique opportunities to reinforce the AI solution’s ethical framework, ensuring a comprehensive defence against potential harms.\nOperating Responsibly: The final stage focuses on the operational deployment of the AI solution, ensuring that its integration into the ecosystem adheres to ethical standards. This involves a thorough review of compliance requirements, the formulation of phased delivery and incident response plans, and the establishment of mechanisms for user feedback and incident management. These steps are crucial for maintaining a responsive and responsible operational framework, ready to address unforeseen challenges proactively. Conclusion\nAdopting a structured, principled approach to generative AI development opens the path for technological innovation that respects ethical boundaries and promotes societal well-being. This guidance on responsible AI underscores the importance of integrating ethical considerations at every stage of AI development and deployment. By rigorously identifying, measuring, mitigating, and operating with a steadfast commitment to ethical principles, we can harness the vast potential of generative AI in a manner that is both innovative and responsible, ensuring that this powerful technology serves the greater good.\ngraph TD A(Identifying Potential Harms) --\u0026gt;|Next| B(Measuring Identified Harms) B --\u0026gt;|Next| C(Mitigating Harms) C --\u0026gt;|Next| D(Operating Responsibly) style A fill:#f9f,stroke:#333,stroke-width:4px style B fill:#bbf,stroke:#333,stroke-width:4px style C fill:#bfb,stroke:#333,stroke-width:4px style D fill:#fbf,stroke:#333,stroke-width:4px A --\u0026amp;gt;|1. Magnifying glass over document| A B --\u0026amp;gt;|2. Bar chart and ruler| B C --\u0026amp;gt;|3. Shield covering a computer chip| C D --\u0026amp;gt;|4. Gear integrating into a network| D\u0026lt;/code\u0026gt;\u0026lt;/pre\u0026gt; ","date":"25 March 2024","externalUrl":null,"permalink":"/exploring-responsible-generative-ai-the-path-to-ethical-innovation/","section":"Articles","summary":"Generative Artificial Intelligence (AI) represents one of the most significant technological advancements, offering capabilities that blur the lines between content generated by machines and humans. As we navigate this new frontier, it’s paramount that we guide this innovation responsibly. Emphasising the principles of responsibility and privacy, this guide provides a comprehensive roadmap for developing AI solutions that are not only advanced but also ethical and responsible.\n","title":"Exploring Responsible Generative AI: The Path to Ethical Innovation","type":"articles"},{"content":"In the ever-evolving landscape of artificial intelligence, Microsoft has once again made headlines with the launch of Phi-2, a groundbreaking small language model (SLM) that is challenging the status quo of what smaller models can achieve. With 2.7 billion parameters, Phi-2 stands out not just for its size but for its remarkable capability to perform at par with, and even outperform, models many times its size. This development represents a significant leap forward in AI, showcasing the potential for compact models to drive innovation and efficiency across various sectors.\nUnveiling Phi-2: A Leap in AI Efficiency Phi-2’s development is rooted in Microsoft’s ambition to create models that are not only powerful but also efficient and accessible. The model is part of Microsoft’s Phi series, a suite of SLMs designed to push the boundaries of AI performance. Compared to its predecessors and contemporaries, Phi-2 has demonstrated unparalleled abilities in reasoning and language understanding, standing tall among base language models with less than 13 billion parameters​​​​​​.\nThe Power of Quality Data and Innovative Scaling At the heart of Phi-2’s success is its strategic approach to training. Unlike conventional methods that heavily rely on the sheer volume of data, Microsoft focused on the quality of the training material. Phi-2 was fed a diet of “textbook-quality” data, comprising synthetic datasets aimed at teaching the model common sense reasoning and general knowledge. This approach, complemented by carefully selected web data filtered for educational value, allowed Phi-2 to achieve its state-of-the-art performance​​.\nMoreover, innovative techniques in scaling up from its precursor, Phi-1.5, enabled the embedding of knowledge within Phi-2, significantly boosting its benchmark scores. This methodological innovation underscores Microsoft’s commitment to advancing AI in ways that prioritize efficiency and effectiveness over mere size​​.\nBenchmarking Success: Phi-2 in Comparison Phi-2’s prowess is not just theoretical. In rigorous academic benchmarks, it has outshined models like Mistral and Llama-2, which possess up to 7B and 13B parameters, respectively. Phi-2’s performance is especially noteworthy in multi-step reasoning tasks, where it has shown superiority over models 25 times its size, including in areas such as coding and mathematics​​​​.\nThis exceptional capability extends to its ethical implications as well. Phi-2 has been trained to exhibit lower levels of toxicity and bias, a significant advancement in addressing some of the most pressing concerns surrounding AI technology today​​.\nThe Future Powered by Phi-2 Despite its impressive achievements, Phi-2 is currently available only for research purposes through Azure AI Studio, underscoring Microsoft’s intention to foster further innovation in the AI field. While its commercial application is limited at this stage, the model represents a pivotal step towards creating more responsible, efficient, and accessible AI technologies.\nPhi-2’s introduction marks an exciting chapter in the story of AI development. By demonstrating that small models can achieve remarkable levels of performance, Microsoft is paving the way for a future where AI can be more widely adopted, offering solutions that are not only powerful but also more sustainable and ethical.\nAs we stand on the brink of this new era, it’s clear that Phi-2 is not just a technological achievement; it’s a beacon of what the future of artificial intelligence could look like. Microsoft’s continued investment in models like Phi-2 promises to bring about innovations that we’re only just beginning to imagine.\n","date":"18 March 2024","externalUrl":null,"permalink":"/phi-2-microsofts-marvel-in-the-world-of-small-language-models/","section":"Articles","summary":"In the ever-evolving landscape of artificial intelligence, Microsoft has once again made headlines with the launch of Phi-2, a groundbreaking small language model (SLM) that is challenging the status quo of what smaller models can achieve. With 2.7 billion parameters, Phi-2 stands out not just for its size but for its remarkable capability to perform at par with, and even outperform, models many times its size. This development represents a significant leap forward in AI, showcasing the potential for compact models to drive innovation and efficiency across various sectors.\n","title":"Phi-2: Microsoft’s Marvel in the World of Small Language Models","type":"articles"},{"content":"In the rapidly evolving world of cloud computing, understanding the essentials of security, compliance, and identity management is crucial. This article delves into the core aspects of the Microsoft Security Compliance and Identity Fundamentals, providing insights into a range of critical topics from Zero Trust models to encryption, ensuring your data remains secure and compliant in the cloud.\n1. The Essence of Zero Trust Model\nExplanation: The Zero Trust model is founded on the principle of never trusting and always verifying. In this environment, every access request is thoroughly vetted as if it originates from an untrusted source, regardless of where the request originates or what resource it accesses. Application: This model is deeply integrated with identity verification, primarily through Azure Active Directory, playing a pivotal role in securing cloud environments. 2. The Shared Responsibility Model\nDetails: This model highlights the collaborative approach to cloud security, where the responsibility is divided between the cloud service provider and the user. While the provider secures the infrastructure, the user must protect their data, applications, and identity management. Significance: Understanding this division of responsibility is key to implementing effective security measures in the cloud. 3. Defence in Depth\nConcept: It refers to a layered approach to security, where multiple security measures and controls are placed throughout the IT system. Implementation: This includes securing physical infrastructures, protecting data with encryption, implementing strong access controls, and continuous monitoring for threats. 4. Understanding Encryption and Cryptography\nOverview: Encryption is the process of encoding data to protect its confidentiality. Cryptography involves creating written or generated codes that allow information to be kept secret. Key Aspects: Includes symmetric and asymmetric encryption, hashing, digital signatures, and the importance of cryptographic keys in securing data. 5. Navigating Through Common Threats and Vulnerabilities\nTypes of Threats: Includes dictionary attacks, DDoS, ransomware, and data breaches. Understanding Vulnerabilities: Focuses on identifying weaknesses in systems that could be exploited by attackers. 6. The Role of Multi-Factor Authentication (MFA)\nFunctionality: MFA enhances security by requiring multiple forms of verification to prove one’s identity. Benefits: Protects against compromised credentials and adds an additional layer of security. 7. Security Information and Event Management (SIEM)\nPurpose: SIEM systems provide real-time analysis and reporting of security alerts. Capabilities: Includes log management, event correlation, and automated alert responses. 8. Intrusion Detection and Prevention Systems (IDPS)\nFunction: Monitors networks for malicious activities and policy violations, and takes action to prevent breaches. Types: Includes signature-based, anomaly-based, and stateful protocol analysis detection methods. 9. The Significance of Cloud Access Security Brokers (CASB)\nRole: Acts as a policy enforcement center, monitoring activity and enforcing security policies between cloud users and cloud applications. Features: Includes monitoring user activity, enforcing security policies, compliance management, and data security. 10. Microsoft Privacy Principles\nPrinciples: Covers control, transparency, security, legal protection, no content-based targeting, and user benefits. Application: Ensures that users have control over their data, and the data is used transparently and for the benefit of the user. Conclusion\nWith an in-depth understanding of Microsoft’s security, compliance, and identity services, individuals and organizations can effectively safeguard their cloud environments. Implementing these principles and strategies is fundamental to maintaining robust security in the cloud.\n","date":"4 December 2023","externalUrl":null,"permalink":"/mastering-microsoft-security-compliance-and-identity-fundamentals/","section":"Articles","summary":"In the rapidly evolving world of cloud computing, understanding the essentials of security, compliance, and identity management is crucial. This article delves into the core aspects of the Microsoft Security Compliance and Identity Fundamentals, providing insights into a range of critical topics from Zero Trust models to encryption, ensuring your data remains secure and compliant in the cloud.\n","title":"Mastering Microsoft Security, Compliance, and Identity Fundamentals","type":"articles"},{"content":"The realm of artificial intelligence (AI) has been a bedrock of transformative technologies, shaping the contours of our digital world. However, a new horizon beckons — Artificial General Intelligence (AGI), an epochal leap from specialized AI systems to machines that can think, learn, and adapt like humans. This blog delves into the technical intricacies and fascinating potential of AGI, poised to redefine the boundaries of what machines can achieve.\nUnderstanding AGI: Beyond Narrow AI Traditional AI systems, often termed as ‘narrow AI’, excel in specific tasks, whether it’s language translation, image recognition, or playing chess. However, they lack the ability to transcend their programmed boundaries. AGI, in contrast, embodies versatility and adaptability — the hallmarks of human intelligence.\nKey Attributes of AGI: Adaptability: AGI systems can operate across diverse environments and problem domains, adapting their learning and decision-making in real-time. Generalization: The prowess of AGI lies in its ability to generalize knowledge from one domain to another, a feat narrow AI struggles with. Autonomous Learning: Unlike narrow AI, which relies heavily on large datasets and specific instructions, AGI can learn autonomously, drawing inferences and acquiring new skills without explicit programming. Contextual Understanding: AGI can comprehend complex, dynamic contexts, allowing it to make decisions in nuanced, real-world situations. Reasoning and Planning: AGI’s ability to reason abstractly and plan strategically marks a significant departure from the reactive nature of narrow AI. The Technical Challenges in Realizing AGI Creating AGI is not merely an extension of current AI technology; it’s a revolutionary stride that demands breakthroughs in several areas:\nAdvanced Algorithms: The development of algorithms that can mimic the human brain’s flexibility and learning efficiency is a formidable challenge. Neuroscience Integration: Understanding and integrating principles from neuroscience is crucial in replicating human-like cognition. Computational Power: AGI requires unprecedented computational capabilities, far beyond what current systems offer. Ethical and Safety Considerations: AGI raises profound ethical questions and safety concerns, necessitating robust frameworks to govern its development and deployment. The Potential Impact of AGI The implications of achieving AGI are profound and far-reaching:\nEconomic and Societal Transformation: From healthcare to education, AGI could revolutionize every sector, driving efficiency, innovation, and solving complex societal challenges. Personalized AI Assistants: Imagine AI assistants that can understand and adapt to individual preferences, offering bespoke advice and support. Scientific Breakthroughs: AGI could accelerate research in fields like climate science, medicine, and physics, uncovering insights beyond human capability. Conclusion: A Vision for the Future Artificial General Intelligence represents the zenith of AI aspirations — a technology that mirrors the depth and adaptability of human intelligence. While the journey towards AGI is fraught with technical and ethical challenges, its potential to transform our world is unparalleled. As we stand at the cusp of this AI revolution, it is crucial to navigate this journey with thoughtful consideration of its impacts on society and the world at large. AGI is not just a technological milestone; it’s a gateway to a future brimming with possibilities yet to be imagined.\n","date":"27 November 2023","externalUrl":null,"permalink":"/exploring-the-frontier-of-artificial-general-intelligence-the-next-leap-in-ai-evolution/","section":"Articles","summary":"The realm of artificial intelligence (AI) has been a bedrock of transformative technologies, shaping the contours of our digital world. However, a new horizon beckons — Artificial General Intelligence (AGI), an epochal leap from specialized AI systems to machines that can think, learn, and adapt like humans. This blog delves into the technical intricacies and fascinating potential of AGI, poised to redefine the boundaries of what machines can achieve.\n","title":"Exploring the Frontier of Artificial General Intelligence: The Next Leap in AI Evolution","type":"articles"},{"content":"In the modern business landscape, the integration of AI technologies demands a commitment to ethical, human-centered practices. The adoption of Responsible AI (RAI) Principles is crucial for ensuring these technologies are used in a way that benefits society, respects individual rights, and promotes sustainability. Below is an expanded look at each of these principles and their importance in the business context.\n1. Human-Centered and Fair Objective: Ensuring AI systems are developed and used in a way that is fair and inclusive.\nInclusive Data Sets: Use diverse data to avoid biases that could lead to unfair outcomes. This includes considering gender, ethnicity, age, and other relevant factors. Diverse Teams: Employ a variety of perspectives in AI development teams to ensure a wide range of viewpoints and experiences are considered. Impact on Diversity and Human Rights: AI should align with and promote the organization’s goals concerning human rights and diversity. Mitigating Unintended Consequences: Regularly assess and adjust AI systems to avoid negative impacts on individuals or groups. 2. Trusted and Transparent Objective: Building trust in AI systems through transparency and accountability.\nVisibility in Data Management: Ensure clarity on how data is collected, stored, and used in AI systems. Explainability: Make AI decisions understandable to both technical and non-technical stakeholders. Accuracy and Soundness: Continuously validate the accuracy and effectiveness of AI systems, ensuring they are based on high-quality data and algorithms. Informed Decision-Making: Enable stakeholders to make informed decisions based on the insights provided by AI. 3. Safe and Secure Objective: Protecting data and individuals from harm.\nSecurity by Design: Integrate security measures at every stage of AI system development and deployment. Data Protection and Privacy: Respect privacy laws and ethical guidelines in the collection and use of data. Contextual Suitability: Ensure AI systems are appropriate for their intended use and environment. Upholding Use Rights: Adhere to legal and ethical standards regarding the use of AI technologies. 4. Open and Accountable Objective: Promoting a culture of responsibility and continuous improvement in AI practices.\nAccountability in AI Practices: Establish clear lines of responsibility for AI-related decisions and outcomes. Traceability: Maintain a clear record of AI development processes and decision-making pathways. Continuous Monitoring and Improvement: Regularly review AI systems for performance, fairness, and ethical considerations. Fostering a Speak-Up Culture: Encourage an environment where concerns about AI systems can be raised and addressed without fear. Implementing Responsible AI Principles To effectively implement these principles, businesses should focus on the following seven dimensions:\nFairness Equitable Outcomes: Ensure AI systems do not perpetuate or exacerbate biases. Case-Specific Definitions: Adapt the definition of fairness based on the specific context and use case of the AI system. Environmental + Social Sustainable Practices: Use AI to support sustainable business practices and decision-making. Balancing Needs: Address the needs of current generations without compromising the ability of future generations to meet their own needs. Transparency Clear Communication: Make the workings of AI systems as transparent as possible. Stakeholder Awareness: Ensure that those affected by AI systems are aware of their interaction with or impact by these systems. Soundness Reliability: Develop AI systems that stakeholders can trust to be accurate and effective. Contextual Relevance: Tailor AI solutions to be relevant and appropriate for their intended application. Robustness Stress Testing: Regularly test AI systems under various conditions to ensure their reliability. Adaptability: Design AI systems to be adaptable to changes in data and environment. Privacy Data Ethics: Handle personal and sensitive data with the utmost care and in compliance with legal standards. Security Measures: Implement strong security measures to protect data from unauthorized access and breaches. Accountability Clear Responsibility: Define who is responsible for the outcomes of AI systems. Redress Mechanisms: Provide clear channels for addressing any issues or grievances related to AI systems. Conclusion By adhering to these expanded RAI principles, businesses can ensure that their use of AI is responsible, ethical, and beneficial to society. This approach not only mitigates risks but also enhances the trust and confidence of customers, stakeholders, and the wider public in AI technologies.\n","date":"23 November 2023","externalUrl":null,"permalink":"/responsible-ai-principles-in-business-a-comprehensive-guide/","section":"Articles","summary":"In the modern business landscape, the integration of AI technologies demands a commitment to ethical, human-centered practices. The adoption of Responsible AI (RAI) Principles is crucial for ensuring these technologies are used in a way that benefits society, respects individual rights, and promotes sustainability. Below is an expanded look at each of these principles and their importance in the business context.\n","title":"Responsible AI Principles in Business: A Comprehensive Guide","type":"articles"},{"content":"","date":"22 November 2023","externalUrl":null,"permalink":"/categories/architecture/","section":"Categories","summary":"","title":"Architecture","type":"categories"},{"content":"As an application architect, navigating the complexities of cloud architecture is a fundamental part of my role. My engagement with Microsoft’s Azure Well-Architected Framework (WAF) has significantly influenced my approach, enabling me to design and implement solutions that are not only efficient and robust but also align with the evolving needs of the business.\nEmbracing Azure WAF in My Role The Azure WAF has been instrumental in shaping my architectural strategies. The framework’s emphasis on combining technical excellence with business value mirrors my own objectives in designing scalable and secure cloud solutions. The recent updates to the framework, particularly in the core pillars and design principles, have provided fresh perspectives and innovative approaches to complex architectural challenges.\nKey Updates and Their Impact The Azure WAF’s recent enhancements have been a game-changer in my architectural process:\nNew Design Principles: These principles have enriched my design toolkit, offering well-vetted approaches for diverse scenarios. Revamped Design Review Checklist: This checklist now mirrors the practical decisions I face daily, making it an invaluable tool. Understanding Pillar Tradeoffs: Balancing the tradeoffs among different architectural aspects is crucial, and the framework provides actionable guidance here. Adopting Design Patterns: The introduction of established architectural patterns has improved the reliability and efficiency of my solutions. Updated Azure Well-Architected Review Tool: This tool is a cornerstone in ensuring my designs stay aligned with the latest industry standards. The Five Pillars: My Architectural Compass Each pillar of the Azure WAF is integral to my architectural design process:\nReliability: I prioritize high uptime and robust recovery capabilities in my designs. Security: Protecting data integrity and maintaining confidentiality is paramount in my work. Cost Optimisation: I constantly strive to deliver cost-effective solutions without compromising on quality. Operational Excellence: My focus is on minimizing production issues through automated systems and comprehensive observability. Performance Efficiency: Adapting swiftly to varying workload demands is key to maintaining optimal performance in my designs. Conclusion The Azure Well-Architected Framework is more than a guideline for me; it’s a catalyst for innovation and strategic thinking. It ensures that my architectural solutions are not just technically proficient but also scalable, secure, and aligned with long-term business objectives. This framework is a testament to Microsoft’s commitment to supporting architects with a robust and adaptable platform for creating advanced cloud solutions. As I continue to tackle the challenges of cloud architecture, the Azure WAF remains an essential part of my toolkit, guiding me towards building sustainable and resilient applications for the Azure platform.\n","date":"22 November 2023","externalUrl":null,"permalink":"/leveraging-the-azure-well-architected-framework-a-personal-journey-as-an-application-architect/","section":"Articles","summary":"As an application architect, navigating the complexities of cloud architecture is a fundamental part of my role. My engagement with Microsoft’s Azure Well-Architected Framework (WAF) has significantly influenced my approach, enabling me to design and implement solutions that are not only efficient and robust but also align with the evolving needs of the business.\n","title":"Leveraging the Azure Well-Architected Framework: A Personal Journey as an Application Architect","type":"articles"},{"content":"In the ever-evolving landscape of e-commerce, integrating intelligent systems has become not just an advantage but a necessity. This is where OpenAI comes into play within a microservices architecture. Let’s delve into a system blueprint and see how OpenAI enriches the e-commerce ecosystem.\nThe E-commerce Microservices Blueprint The blueprint under consideration is a comprehensive microservices architecture for a cloud-based e-commerce platform. It segregates the application into several independent services, each responsible for a discrete business capability, thereby facilitating scalability, maintainability, and resilience. Here’s a more detailed walkthrough:\nClient Apps: Mobile and browser applications represent the front end, providing user interfaces tailored to different devices.\nCloud Services:\nIdentity Service: This critical service maintains security, handling user authentication and authorization through its Identity API, backed by a PostgreSQL database. Catalog Service: Serving as the product directory, the Catalog API interacts with its PostgreSQL database to deliver product listings. Order Service: Central to e-commerce, the Ordering API and its Order Processor handle everything from cart management to order finalisation. Basket Service: This utilises a Redis data store for its speed in managing temporary basket data. Payment Service: The Payment Processor is key to secure financial transactions. Admin Services: They maintain the business logic for admin operations, with Webhooks API enabling real-time event notification.\nEvent Bus: A message bus for services to publish and subscribe to events, ensuring a decoupled system.\nObservability: Monitors system health and performance, critical for service reliability.\nThe Role of OpenAI In this architecture, OpenAI serves as a powerful ally, bringing cutting-edge AI capabilities to the table. Here’s how OpenAI can be utilised across different services:\nPersonalisation: By analysing user interactions and purchase history, OpenAI can tailor product recommendations, enhancing the user experience and boosting sales. Customer Service: OpenAI’s conversational models can power chatbots to provide instant customer support, handling inquiries and troubleshooting common issues. Inventory Management: Predictive models can forecast demand, helping maintain optimal inventory levels. Fraud Detection: AI can identify patterns indicative of fraudulent transactions, thereby securing the payment process. Content Generation: Product descriptions, reviews, and promotional content can be scaled using OpenAI’s language models. How is OpenAI Integrated? Integrating OpenAI into the ecosystem involves setting up an API gateway that allows secure interaction between the OpenAI service and the e-commerce microservices.\nIdentity Service: Utilising OpenAI, we can enhance security protocols by implementing advanced behavioural analytics to detect anomalies in user behaviour, suggesting potential security breaches.\nCatalog Service: Language models can generate creative product descriptions, making listings both informative and engaging.\nOrder Service: AI can optimise routing and logistics for order delivery by predicting the fastest and most cost-effective routes.\nBasket Service: Cognitive models can analyse basket data to suggest additional items, increasing average order value.\nPayment Service: By implementing AI-driven algorithms, the system can detect and prevent fraudulent transactions in real-time.\nAdmin Services: Natural language processing can streamline the management of customer feedback and automate responses to common queries.\nEvent Bus: AI can process event streams to identify patterns, trigger workflows, or alert administrators to significant occurrences.\nObservability: AI models can predict system failures before they happen by analysing logs and performance data, facilitating proactive maintenance.\nIn Conclusion Incorporating OpenAI into a microservices architecture transforms a standard e-commerce platform into an intelligent ecosystem that not only understands and reacts to user behaviour but also anticipates needs, automates processes, and provides invaluable insights. It’s a strategic move that can dramatically enhance the efficiency of operations, the effectiveness of marketing, and the satisfaction of customers. The future of e-commerce lies in such smart integrations, where artificial intelligence becomes the backbone of customer engagement and operational excellence.\n","date":"15 November 2023","externalUrl":null,"permalink":"/integrating-openai-into-e-commerce-a-microservices-approach/","section":"Articles","summary":"In the ever-evolving landscape of e-commerce, integrating intelligent systems has become not just an advantage but a necessity. This is where OpenAI comes into play within a microservices architecture. Let’s delve into a system blueprint and see how OpenAI enriches the e-commerce ecosystem.\n","title":"Integrating OpenAI into E-commerce: A Microservices Approach","type":"articles"},{"content":"","date":"29 October 2023","externalUrl":null,"permalink":"/categories/chatgpt/","section":"Categories","summary":"","title":"ChatGPT","type":"categories"},{"content":"If you’re looking to extract the maximum potential from ChatGPT, you’re in the right place. In this post, I’ll walk you through a systematic approach to forming your prompts.\nStep 1: Role with a Speciality When interacting with ChatGPT, specificity is your friend. It’s not enough to merely state a role, like ‘copywriter’; you’ll fare much better if you specify a speciality within that role. For instance, instead of saying “You are a copywriter,” try “You are a copywriter who specialises in writing high-converting sales copy.” This will steer the model toward generating output that is more tailored to your needs.\nStep 2: Task Once you’ve identified the role with a speciality, you need to specify the task you’d like the model to perform. Clarity and conciseness are crucial here. The more detailed and specific you can be about the task, the better the results you’re likely to get.\nStep 3: Desired Outcome You’ll also need to elucidate what you’re hoping to achieve. Whether it’s generating leads, crafting an article, or solving a complex problem, make your desired outcome explicit. This provides ChatGPT with the context it needs to generate output that aligns closely with your objectives.\nStep 4: Format If you have a preference for how the output should be formatted, now is the time to state it. Whether you want the output in Markdown, table form, or some other layout, specifying the format will make the output easier to read and utilise.\nStep 5: Questions A common misconception is that the model should get it right the first time and not need to ask questions for clarification. In reality, it’s quite helpful to instruct ChatGPT to ask you as many questions as necessary to get the best possible outcome. If your prompt is already well-crafted, it may not need to ask any questions at all. But it’s always a good idea to open that door.\nStep 6: Data Feeding If you have specific data that could enrich the context, by all means, include it. For example, if you’re asking for a sales letter for a solar business, providing some details about your product offerings and business goals can lead to a more nuanced and effective result.\nExample Prompt Here’s how you might string all these elements together:\n” You are a copywriter who specialises in writing high-converting sales copy. Write a sales letter to promote my solar business. I want to generate leads from this sales letter. Format the letter in Markdown. Feel free to ask me as many questions as you like for the best possible outcome.”\nBy constructing your prompt this way, you give the model ample context, allowing it to generate an output that is both specific to your needs and easier to read.\nGet GPT to ask you the questions “Your role is to ask me seven questions and then act on those questions to generate a good response: What role should the ChatGPT model play for this task? What speciality within that role would be most beneficial for my needs? What is the specific task I want to be completed? What is my desired outcome from this task? Is there a particular format in which I want the output delivered? Are there any questions the model should ask me for further clarification? Do I have any specific data to include for a more contextual and precise result? Once you provide these questions, it’ll help me better structure my main prompt for more accurate and detailed outputs. Tell me you understand what I need you to do”\nThe Often-Missed Trick Here’s the part most people miss: Don’t settle for the first answer if it doesn’t meet your expectations. ChatGPT doesn’t have feelings, so if the output isn’t up to snuff, let it know. Give feedback and you’ll often find that it ‘steps up its game,’ delivering a much-improved response on the second try.\nBy employing this six-step framework and being willing to iterate, you’ll be well-equipped to maximise the effectiveness of your interactions with ChatGPT.\nHappy prompting!\n","date":"29 October 2023","externalUrl":null,"permalink":"/how-to-craft-the-perfect-chatgpt-prompt-for-maximum-output/","section":"Articles","summary":"If you’re looking to extract the maximum potential from ChatGPT, you’re in the right place. In this post, I’ll walk you through a systematic approach to forming your prompts.\nStep 1: Role with a Speciality When interacting with ChatGPT, specificity is your friend. It’s not enough to merely state a role, like ‘copywriter’; you’ll fare much better if you specify a speciality within that role. For instance, instead of saying “You are a copywriter,” try “You are a copywriter who specialises in writing high-converting sales copy.” This will steer the model toward generating output that is more tailored to your needs.\n","title":"How to Craft the Perfect ChatGPT Prompt for Maximum Output","type":"articles"},{"content":"Are you ever hesitant to test new software or visit unfamiliar websites due to concerns about potential harm to your computer? Microsoft has your back with Windows 11 Sandbox, a feature that allows you to create a secure and isolated virtual environment for experimenting with software and browsing the web without putting your primary system at risk. In this blog post, we’ll dive into what Windows 11 Sandbox is and how you can access and use it on your Windows 11 Pro, Enterprise, or Education edition.\nWhat is Windows 11 Sandbox? Windows 11 Sandbox is like a protective cocoon for your computer. It’s a virtualized environment that enables you to run applications and carry out tasks within a self-contained, isolated space. This means any changes or potentially harmful actions you take in the Sandbox stay within it and won’t affect your main Windows installation.\nAccessing Windows 11 Sandbox: A Step-by-Step Guide 1. Check System Requirements:\nBefore you get started, make sure your computer meets these prerequisites:\nA Windows 11 Pro, Enterprise, or Education edition. A 64-bit processor with virtualization capabilities enabled in BIOS. At least 4GB of RAM (8GB or more recommended). Virtualization technology (such as Intel VT-x or AMD-V) should be enabled in your computer’s BIOS settings. 2. Enable Virtualization:\nIf virtualization isn’t already enabled in your computer’s BIOS settings, you’ll need to restart your computer and access the BIOS/UEFI settings to enable it. The exact steps can vary depending on your computer’s manufacturer, so consult your motherboard or PC manual for guidance.\n3. Enable Windows Sandbox Feature:\nOpen the Windows 11 Start menu and go to “Settings.” 4. Navigate to “Apps” \u0026gt; “Optional Features”:\nIn the Settings window, click on “Apps” and then select “Optional Features.” 5. Enable “Windows Sandbox”:\nScroll down the list of optional features and find “Windows Sandbox.” Click on it, and then click the “Install” button to enable the feature. 6. Restart Your Computer:\nAfter enabling Windows Sandbox, restart your computer to complete the setup. 7. Launch Windows 11 Sandbox:\nOnce your computer has restarted, open the Start menu and type “Windows Sandbox.” You should see it in the search results. Click on it to launch the Sandbox. 8. Use Windows 11 Sandbox:\nWindows Sandbox will open, providing you with a clean, isolated Windows environment. You can now install and run applications within this environment, and any changes made here will not affect your main Windows installation. 9. Closing Windows Sandbox:\nWhen you’re done with the Sandbox, simply close it as you would any other application. Windows will discard the temporary environment and any changes made within it. Conclusion Windows 11 Sandbox is a powerful tool for users who want to explore new software, visit potentially risky websites, or carry out other tasks in a secure and isolated environment. With its straightforward setup process and the peace of mind it offers, you can take risks and experiment without fear of damaging your primary Windows system. So, go ahead and unleash your curiosity in the safe haven of Windows 11 Sandbox!\n","date":"29 October 2023","externalUrl":null,"permalink":"/exploring-the-safe-haven-of-windows-11-sandbox/","section":"Articles","summary":"Are you ever hesitant to test new software or visit unfamiliar websites due to concerns about potential harm to your computer? Microsoft has your back with Windows 11 Sandbox, a feature that allows you to create a secure and isolated virtual environment for experimenting with software and browsing the web without putting your primary system at risk. In this blog post, we’ll dive into what Windows 11 Sandbox is and how you can access and use it on your Windows 11 Pro, Enterprise, or Education edition.\n","title":"Exploring the Safe Haven of Windows 11 Sandbox","type":"articles"},{"content":"Adding a layer of depth to our understanding of Responsible AI in the charity sector are insights from experts in the field. Their collective wisdom emphasises that the practice of Responsible AI is not merely a modern phenomenon; it has a historical backdrop dating back to the 1960s.\nHistorical Context The discussion around responsible AI is not a new topic; it dates back several decades. During this time, the focus has shifted from theoretical discussions to practical implementation. We are the generation that has the opportunity, and the responsibility, to implement these ethical guidelines and principles in our daily work.\nRegulatory Guidance AI-specific regulations, such as the AI Act, provide structured guidance on how to differentiate between prohibited, high-risk, and other categories of AI implementations. They offer frameworks for identifying and mitigating associated risks, thereby aiding organisations in maintaining public trust.\nValues and Principles One profound insight from the experts is the potential for AI to be more than just a tool; it can be a manifestation of an organisation’s values and principles. Often, values are expressed in documents and are the subject of occasional executive discussions but are not deeply integrated into the organisation’s daily operations. With AI, there is an opportunity to “programme” these values and principles into the technology itself. This way, they serve as a ‘North Star’ guiding the organisation, thereby differentiating it in the landscape.\nAI Governance It is also suggested that creating a specific function dedicated to AI governance could be invaluable. Such a role could oversee new processes to ensure they align with an organisation’s core values, helping to clarify these principles in real and tangible ways.\nThe Importance of Curiosity As the field of AI is fast-moving, staying informed and curious is crucial. The landscape is not perfectly formed; thus, it is important to ask questions continuously, learn, and consult various sources, including service providers and peers in the sector. This proactive approach allows for a nuanced and well-rounded understanding of how to implement AI responsibly.\nConclusion The incorporation of these expert insights amplifies the importance of approaching AI with a multi-faceted perspective. It’s not just about the technology; it’s about aligning it with an organisation’s historical context, regulations, and above all, its values and principles. As we strive to make strides in the charity sector through AI, keeping these multi-dimensional insights at the forefront is indispensable for ethical and effective implementation.\n","date":"28 September 2023","externalUrl":null,"permalink":"/the-multidimensional-task-of-responsible-ai-expert-insights/","section":"Articles","summary":"Adding a layer of depth to our understanding of Responsible AI in the charity sector are insights from experts in the field. Their collective wisdom emphasises that the practice of Responsible AI is not merely a modern phenomenon; it has a historical backdrop dating back to the 1960s.\n","title":"The Multidimensional Task of Responsible AI: Expert Insights","type":"articles"},{"content":"Artificial Intelligence (AI) has become an integral part of our daily lives, from email suggestions to navigation apps and even in government systems. However, as David Ngure’s insightful article “Are AI-Generated Images Biased?” points out, the technology is far from perfect. One of the most pressing issues is the inherent bias in AI systems, which can have severe societal implications. This blog post aims to delve deeper into AI bias, taking cues from Ngure’s research and proposing a way forward to tackle this issue.\nHow Common is Bias in AI? Bias in AI is a widespread issue that shows up in many different areas. David Ngure’s research focused on how AI tools that create images often produce results that are influenced by stereotypes about gender and race. For example, when the word “nurse” was used, the AI mostly showed pictures of women. On the other hand, the word “CEO” mostly brought up images of men.\nBut it’s not just about pictures. Bias in AI has been found in other sectors, too, like healthcare, job hiring, and law enforcement. For instance, some algorithms used in the legal system have been found to be unfair to black people.\nSo, it’s clear that bias in AI is a big problem that we encounter in various ways, and we need to pay attention to it.\nThe Human Element in AI Bias The root of the problem lies in the data used to train these AI systems. AI is only as good as the data it learns from, and if that data is biased, the AI will inevitably inherit those biases. Ngure rightly points out that the people who develop and interact with these programs are full of biases, which the machines pick up.\nThe Impact of AI Bias The consequences of AI bias are far-reaching. A biased AI can perpetuate existing societal stereotypes and prejudices. For example, if an AI tool only shows white men as CEOs or black men as basketball players, it can be used to affirm pre-existing viewpoints, leading to a vicious cycle of bias and discrimination.\nA Way Forward: Tackling AI Bias Diverse Teams Companies should strive for diversity in all departments, especially in coding and quality assurance teams. A diverse team is more likely to spot and correct biases in AI systems.\nScrutinising Training Data Before feeding data into AI systems, it should be carefully examined for biases. This will require a multi-disciplinary approach involving data scientists, ethicists, and domain experts.\nGovernance and Monitoring AI systems should be governed by ethical guidelines and monitored continuously for biases. Users should also have a direct avenue for feedback, and companies should have procedures for quickly addressing bias-related complaints.\nPublic Awareness and Education Public awareness about the issue of AI bias needs to be raised. Educational institutions should focus on getting more girls, children of colour, and children from diverse backgrounds interested in computer science. This will eventually lead to a more diverse set of people shaping the future of technology.\nConclusion While eliminating bias in AI may be a tall order, being aware of it and taking proactive steps can significantly reduce its harmful impact. As Ngure’s article suggests, the technology is still in its early stages, making it the perfect time to address these issues head-on. By adopting a multi-pronged approach that involves diverse teams, scrutinised training data, and public awareness, we can hope to build AI systems that are as unbiased as possible.\n","date":"28 September 2023","externalUrl":null,"permalink":"/tackling-the-bias-in-ai-a-comprehensive-look-and-way-forward/","section":"Articles","summary":"Artificial Intelligence (AI) has become an integral part of our daily lives, from email suggestions to navigation apps and even in government systems. However, as David Ngure’s insightful article “Are AI-Generated Images Biased?” points out, the technology is far from perfect. One of the most pressing issues is the inherent bias in AI systems, which can have severe societal implications. This blog post aims to delve deeper into AI bias, taking cues from Ngure’s research and proposing a way forward to tackle this issue.\n","title":"Tackling the Bias in AI: A Comprehensive Look and Way Forward","type":"articles"},{"content":"Artificial Intelligence (AI) has emerged as a transformative technology, influencing various industries and revolutionising how we live and work. However, the rapid adoption of AI technologies also brings many risks that must be carefully managed. This blog aims to provide a comprehensive overview of these risks and practical suggestions for their mitigation.\nIntroduction The purpose of this blog is to shed light on the common risks associated with the use of Artificial Intelligence. These risks are categorised into six main areas: Privacy, Security, Accountability, Fairness, Transparency, and Unintended Consequences. Each section will discuss the risk’s importance, elaborate on its challenges, and offer mitigation strategies.\nPrivacy Privacy is the most critical risk because personal or sensitive data misuse can have immediate and severe consequences for individuals. AI systems often require extensive datasets, including personal or sensitive information. The risk here lies in potential data breaches or unauthorised access, which could expose this sensitive data and cause harm to individuals.\nOrganisations should implement strict privacy policies and protocols that comply with data protection laws to mitigate this risk. Encryption techniques should also be used to secure data, and users should be able to control what data is collected and how it is used.\nSecurity Security is essential for maintaining the integrity of AI systems and the data they process. AI systems are vulnerable to hacking, malware, and other forms of cyber-attacks, which could compromise the system’s functionality and the safety of the data it processes.\nRobust security protocols should be employed, including firewalls and intrusion detection systems. Regular security audits should be conducted to identify and fix vulnerabilities, and staff should be trained in cybersecurity best practices.\nAccountability Accountability is crucial for establishing trust in AI systems. When AI systems operate autonomously, determining responsibility for any mistakes or ethical lapses becomes complex, often leading to a lack of accountability.\nTo address this, the roles and responsibilities of those involved in developing and deploying AI systems should be clearly defined. Mechanisms for oversight, such as third-party audits, should be established, and a system for logging decisions made by the AI should be implemented for future review.\nFairness Fairness ensures that AI systems do not perpetuate or exacerbate existing social inequalities. AI algorithms can inherit biases in their training data or their designers, leading to unfair or discriminatory decisions.\nTo mitigate this, thorough bias assessments should be conducted on the training data. Diverse and representative data sets should be used, and algorithms designed to be fair should be implemented and regularly updated to reduce bias.\nTransparency Transparency is necessary for building trust and enabling the identification and correction of errors or biases. The “black box” nature of some AI algorithms makes understanding how decisions are made difficult.\nTo improve transparency, clear and accessible explanations of how the AI system works should be provided. The data types and algorithms used should be disclosed, and user access to this information should be enabled where appropriate.\nUnintended Consequences While unintended consequences are often unpredictable, they can have a significant impact. AI systems can sometimes behave in ways their designers did not anticipate, leading to unintended and potentially harmful outcomes.\nTo address this, a diverse group of stakeholders should be involved in the design and testing phases. Risk assessments should be conducted to identify potential unintended consequences, and the system’s performance should be monitored and adjusted as needed.\nConclusion The rapid advancement of AI technologies offers immense benefits but presents a range of risks that must be carefully managed. By being aware of these risks and taking proactive steps to mitigate them, organisations can harness AI’s full potential in a fair, transparent, and secure manner.\n","date":"6 September 2023","externalUrl":null,"permalink":"/understanding-the-common-risks-associated-with-artificial-intelligence-ai/","section":"Articles","summary":"Artificial Intelligence (AI) has emerged as a transformative technology, influencing various industries and revolutionising how we live and work. However, the rapid adoption of AI technologies also brings many risks that must be carefully managed. This blog aims to provide a comprehensive overview of these risks and practical suggestions for their mitigation.\n","title":"Understanding the Common Risks Associated with Artificial Intelligence (AI)","type":"articles"},{"content":"","date":"29 August 2023","externalUrl":null,"permalink":"/categories/github/","section":"Categories","summary":"","title":"GitHub","type":"categories"},{"content":"In the ever-evolving landscape of software development, open-source projects often find themselves grappling with sustainability issues. While sponsorship models have emerged as a viable solution, they sometimes raise ethical and security concerns. One such example is the SponsorLink feature in Moq, a popular mocking framework for .NET. A Reddit post recently brought attention to this feature, sparking a debate on its ethical implications. This blog post aims to dissect the issue and provide a balanced perspective.\nWhat is Moq? Moq is a widely-used mocking framework in the .NET ecosystem. It allows developers to create mock objects for unit testing, facilitating the isolation of code under test from external dependencies. Its ease of use and robust features have made it a go-to choice for many .NET developers.\nThe SponsorLink Controversy The controversy began when a Reddit user updated Moq in one of their projects and received a warning about not having installed a GitHub Sponsors app. Upon further investigation, they discovered that Moq, starting from version 4.20, includes a .NET analyser that scans the local git config during the build process. This analyser extracts the user’s email address and sends it to a service hosted in Azure to check if the user is a sponsor.\nEthical Concerns Data Privacy The most glaring issue is the potential infringement on data privacy. Extracting and sending email addresses without explicit consent could be considered a violation of privacy norms and potentially even data protection laws, depending on the jurisdiction.\nSecurity Risks The feature also introduces a potential security risk. By sending data to an external service, it opens up a new attack vector that could be exploited in a supply chain attack.\nTransparency Another concern is the lack of transparency. Users were not explicitly informed about this new feature, discovering it only after updating the package and receiving a warning.\nThe Other Side of the Coin Sustainability Open-source projects often struggle with sustainability. Sponsorship models like SponsorLink could provide a lifeline for maintaining and improving the project.\nOpting Out It’s worth noting that users can potentially opt out of this feature, although the process for doing so is not straightforward.\nConclusion While the intention behind SponsorLink may be to sustain the Moq project, its implementation raises several ethical and security concerns. Transparency and user consent should be at the forefront of any such feature. As the debate continues, it serves as a cautionary tale for other open-source projects considering similar sponsorship models.\nLet’s hope that the Moq team and the broader .NET community can arrive at a solution that balances the need for sustainability with ethical considerations.\n","date":"29 August 2023","externalUrl":null,"permalink":"/the-ethical-implications-of-moqs-sponsorlink-feature-a-deep-dive/","section":"Articles","summary":"In the ever-evolving landscape of software development, open-source projects often find themselves grappling with sustainability issues. While sponsorship models have emerged as a viable solution, they sometimes raise ethical and security concerns. One such example is the SponsorLink feature in Moq, a popular mocking framework for .NET. A Reddit post recently brought attention to this feature, sparking a debate on its ethical implications. This blog post aims to dissect the issue and provide a balanced perspective.\n","title":"The Ethical Implications of Moq’s SponsorLink Feature: A Deep Dive","type":"articles"},{"content":"Generative artificial intelligence (AI) models like ChatGPT have exploded in popularity in recent months. These AI systems can generate synthetic text, images, audio and video that closely resembles human-created content. Major tech companies are racing to integrate generative AI into their platforms and services. But this rapid development and deployment raises serious concerns about potential consumer harm that must be addressed.\nIn a new report, the Norwegian Consumer Council highlights the consumer angle of generative AI. While these systems may provide some benefits, they also introduce vast risks. The report describes challenges relating to:\nPower concentration in the hands of big tech companies, who gain significant control over generative AI systems. This allows them to potentially entrench their dominant positions. Lack of transparency and accountability. Generative AI systems are often opaque “black boxes”, making it hard to audit them for errors, bias and other issues. Manipulation of consumers through techniques like deepfakes or anthropomorphised chatbots designed to influence emotions and opinions. Biases and discrimination that can be replicated or introduced, due to issues with training data or content moderation practices. Privacy violations, with personal data often used without proper consent to develop the models. Security vulnerabilities that could facilitate new types of fraud and cybercrime. Replacing human roles like moderators and creators with automated systems, which may reduce quality and exploit precarious labour. Environmental harms from the massive computing power required to develop and run these AI models. To address these concerns, the report calls for better enforcement of existing regulations like consumer protection, data protection and product safety laws when applied to generative AI systems. It also recommends new safeguards like transparency requirements, impact assessments before deployment, and making developers responsible for harms.\nAs consumers start interacting with generative AI on a regular basis, it’s crucial that policymakers act swiftly to minimise risks and ensure these systems respect consumer rights. The report provides a timely overview of key issues and recommendations for oversight of this rapidly evolving technology.\nGHOST_IN_THE-MACHINE_Addressing_the_consumer_harms_of_generative_AIDownload ","date":"22 August 2023","externalUrl":null,"permalink":"/the-rapid-rise-of-generative-ai-and-its-risks-for-consumers/","section":"Articles","summary":"Generative artificial intelligence (AI) models like ChatGPT have exploded in popularity in recent months. These AI systems can generate synthetic text, images, audio and video that closely resembles human-created content. Major tech companies are racing to integrate generative AI into their platforms and services. But this rapid development and deployment raises serious concerns about potential consumer harm that must be addressed.\n","title":"The Rapid Rise of Generative AI and Its Risks for Consumers","type":"articles"},{"content":"As a technical consultant advising clients on AI solutions, the implications of the new blueprint on governing AI proposed by Microsoft are significant. While bringing exciting new capabilities, AI also creates new responsibilities. As trusted advisors to clients, it’s important we stay up-to-date on the evolving laws, regulations and best practices around responsible AI development.\nSeveral parts of the blueprint stand out as being particularly relevant:\nThe implementation of standard AI safety frameworks will require us to get smart on frameworks like the NIST AI Risk Management Framework. We’ll need to understand the requirements and attestation processes in order to guide clients on compliance. For clients operating in critical infrastructure like energy, new safety brake requirements will be an important consideration in solution design. We’ll need to advise clients on risk assessment processes and building human oversight controls into AI systems. Proposed licensing of AI data centers adds another layer we’ll need to keep in mind. As regulations develop that differentiate obligations by role in the AI tech stack, we’ll need to map client scenarios accordingly. For powerful AI models, we may need to help clients navigate licensing and required safety reviews by new regulators. There may also be knock-on effects to how clients utilise AI cloud infrastructure. Expectations around transparency, like AI impact reports, will create new advisor responsibilities. We can help clients implement ethical AI practices that instill public trust and fulfill regulatory requirements. Guiding clients to provide meaningful transparency into AI systems should become a bigger part of our work. AI-powered initiatives to address major societal issues will create new opportunities for clients and demand for our expertise. We can connect clients to emerging public-private ventures where AI can drive progress on challenges like environmental sustainability. This blueprint underscores how essential it is that we continue developing our own knowledge of responsible and ethical AI design patterns. We must help clients navigate rapidly evolving expectations. By steering clients to develop AI responsibly and beneficially from the start, we can play a big role in realising AI’s promise while mitigating risks. Trust in AI depends in large part on the guidance of advisors like us.\nGoverning-AI-A-Blueprint-for-the-FutureDownload ","date":"31 July 2023","externalUrl":null,"permalink":"/governing-ai-what-this-means-for-technical-consultants/","section":"Articles","summary":"As a technical consultant advising clients on AI solutions, the implications of the new blueprint on governing AI proposed by Microsoft are significant. While bringing exciting new capabilities, AI also creates new responsibilities. As trusted advisors to clients, it’s important we stay up-to-date on the evolving laws, regulations and best practices around responsible AI development.\n","title":"Governing AI: What This Means For Technical Consultants","type":"articles"},{"content":"","date":"18 July 2023","externalUrl":null,"permalink":"/categories/data/","section":"Categories","summary":"","title":"Data","type":"categories"},{"content":"In today’s data-driven world, companies live or die based on how well they utilise data. Organisations like Google, Amazon and Netflix owe their success largely to data analytics. They uncovered game-changing insights that propelled them to dominance.\nMost companies, however, fail to harness the full potential of their data. Valuable information gets stranded in disparate systems that don’t interconnect. IT teams burn time and money attempting to integrate these fragmented data sources. Security and compliance risks increase. Worst of all, companies miss out on the critical insights needed to compete and thrive.\nWhat if you could bring all your data together into a unified, intelligent platform? One that seamlessly shares data across operational systems, analytics tools, reporting applications and AI algorithms. Information flows freely to where it’s needed most. Silos get eliminated. Strategic insights emerge. This is the promise of an intelligent data platform.\nWith a unified data platform, you gain a comprehensive view of your business. Key metrics come alive on interactive dashboards. You can drill down to uncover root causes. Predictive models surface trends you never knew existed. Your analysts have the self-service access they need to find answers. Data democratisation empowers your entire workforce.\nAn intelligent data platform doesn’t just transform data – it revolutionises your decision making. You uncover game-changing insights that disrupt your industry. You boost efficiency by optimising processes. You delight customers by anticipating their needs. You accelerate innovation through data-driven experimentation. Equipped with better information, you make strategic decisions that propel your business into the future.\nNow is the time to tap into the power of your data. Don’t let it sit trapped in silos, its value wasted. Bring it together under one roof. Let it flow openly to users enterprise-wide. Build a data-driven culture of analytics. Give your teams the tools and information they need to drive real competitive advantage. Construct a foundation for the future with an intelligent data platform.\nThe companies that act now to unify their data will be the industry leaders of tomorrow. Don’t get left behind. Leverage your data today to maximise its strategic impact. Comprehensive analytics and enterprise-wide sharing are now within reach. Unlock your data’s true potential with an intelligent platform built for the modern data era. The future starts today.\nIntroduction-to-Intelligent-Data-PlatformsDownload ","date":"18 July 2023","externalUrl":null,"permalink":"/unlocking-the-power-of-data-with-an-intelligent-platform/","section":"Articles","summary":"In today’s data-driven world, companies live or die based on how well they utilise data. Organisations like Google, Amazon and Netflix owe their success largely to data analytics. They uncovered game-changing insights that propelled them to dominance.\n","title":"Unlocking the Power of Data with an Intelligent Platform","type":"articles"},{"content":"Artificial intelligence has taken big leaps forward in recent years. One of the most exciting and friendly new AI systems is Claude, created by the AI research company Anthropic. Claude is an AI assistant designed to be helpful, harmless, and honest.\nhttps://claude.ai/\nClaude was first released to the public in February 2023. It uses an approach called Constitutional AI that gives Claude built-in safeguards to prevent unethical behaviour. This makes Claude stand out from previous AI systems that lacked robust safety measures.\nMany people have been impressed with Claude’s conversational abilities. It can understand natural language, answer questions knowledgeably, and have pleasant chit-chat. Unlike some overhyped AI bots, Claude seems to live up to its claims of intelligence.\nSome of Claude’s capabilities include:\nUnderstanding complex speech and text Providing helpful info to users’ questions Admitting when it doesn’t know something Refusing unethical commands from users Discussing AI safety issues transparently Anthropic trained Claude using a massive dataset called the Constitutional Corpus. This contains over 1.5 billion curated dialogue examples to ensure Claude is helpful and honest. Anthropic also used advanced techniques like self-supervised learning to improve Claude.\nSo far, Claude looks like an impressive showcase of safe and friendly AI. Its transparent nature and Constitutional AI approach could set a new standard for ethical assistants. As Claude expands its skills, it may point towards a future where people can trust AI to be both capable and kind.\n","date":"14 July 2023","externalUrl":null,"permalink":"/claude-the-ai-assistant-from-anthropic/","section":"Articles","summary":"Artificial intelligence has taken big leaps forward in recent years. One of the most exciting and friendly new AI systems is Claude, created by the AI research company Anthropic. Claude is an AI assistant designed to be helpful, harmless, and honest.\n","title":"Claude – The AI Assistant from Anthropic","type":"articles"},{"content":"As a developer, you may want to create intelligent applications that can see, hear, speak, and comprehend natural language. You might assume that achieving this requires extensive AI or data science expertise. However, I’m here to inform you that you can incorporate AI capabilities into your applications with just a few lines of code.\nEnter Azure Cognitive Services, a cloud-based AI service suite that offers prebuilt models and APIs for various cognitive scenarios. Whether your objective is to analyze images, transcribe speech, translate text, or generate natural language responses, Azure Cognitive Services has the solution you need.\nIn this blog post, I will provide an overview of Azure Cognitive Services, its capabilities, and how you can leverage them in your applications.\nWhat Are Azure Cognitive Services? Azure Cognitive Services is a collection of AI services designed to assist developers in integrating cognitive intelligence into applications without requiring direct AI or data science expertise. These services can be accessed through REST APIs and client library SDKs, supporting popular development languages.\nWith Azure Cognitive Services, developers can effortlessly incorporate cognitive features into their applications, enabling them to perceive, listen, speak, search, understand, and accelerate advanced decision-making.\nAzure Cognitive Services can be categorized into five main areas:\nVision: These services provide advanced computer vision algorithms for image processing and information retrieval. For instance, the Computer Vision service facilitates the extraction of text from images using optical character recognition (OCR), while the Face service enables face detection and photo recognition. Speech: These services introduce speech-enabled features to applications. For example, the Speech service can convert speech to text or text to speech, while the Speech Translation service allows real-time speech translation from one language to another. Language: These services offer various natural language processing (NLP) capabilities for understanding and analyzing text. The Language Understanding service, for instance, enables the development of conversational AI agents that can interpret user intents and entities from natural language input. Additionally, the QnA Maker service allows the creation of question-and-answer bots based on existing content. Decision: These services assist in monitoring and detecting anomalies in data, moderating content for potentially offensive or risky material, and personalizing user experiences based on behaviour. The Anomaly Detector service, for example, can identify unusual patterns in time series data, while the Personalizer service aids in selecting the most suitable content or action to present to users. Azure OpenAI Service: This service grants access to the powerful OpenAI models capable of generating natural language responses based on input. With the Azure OpenAI Service, you can create summaries, captions, headlines, stories, lyrics, code snippets, and more. How to Utilise Azure Cognitive Services? You’ll need an Azure account and a subscription key for the desired service to use Azure Cognitive Services. You can begin with an Azure free account, which provides a $200 credit to use within 30 days, along with free usage of many services.\nOnce you have your account and subscription key, select the API or SDK that aligns with your development language and platform. Documentation and quickstarts for each service can be found on the Azure Cognitive Services website.\nHere’s an example of how to use the Computer Vision service in C#:\nusing System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { // Set the API endpoint and subscription key string endpoint = \u0026ldquo;https://\u0026lt;your-region\u0026gt;.api.cognitive.microsoft.com/\u0026rdquo;; string subscriptionKey = \u0026ldquo;\u0026lt;your-subscription-key\u0026gt;\u0026rdquo;;\n// Set the API URL string visionUrl = $\u0026quot;{endpoint}vision/v3.2/analyze\u0026quot;; // Set the image URL string imageUrl = \u0026quot;https://upload.wikimedia.org/wikipedia/commons/thumb/1/12/Broadway_and_Times_Square_by_night.jpg/450px-Broadway_and_Times_Square_by_night.jpg\u0026quot;; // Set the parameters for the API request string parameters = \u0026quot;visualFeatures=Categories,Description\u0026quot;; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add(\u0026quot;Ocp-Apim-Subscription-Key\u0026quot;, subscriptionKey); // Make the API request HttpResponseMessage response = await client.PostAsJsonAsync($\u0026quot;{visionUrl}?{parameters}\u0026quot;, new { url = imageUrl }); // Get the response content as a JSON object var result = await response.Content.ReadAsAsync\u0026amp;lt;dynamic\u0026amp;gt;(); // Print the response Console.WriteLine(result); } } } Make sure to replace \u0026lt;your-region\u0026gt; with the appropriate region and \u0026lt;your-subscription-key\u0026gt; with your actual subscription key. This code sends a POST request to the Computer Vision service API and retrieves the response, which can then be processed or displayed as needed.\nNote: To run this code, you must have the Newtonsoft.Json package installed. You can add it to your project using NuGet.\nAs demonstrated, the Computer Vision service can analyze an image and provide information such as categories, tags, and captions that describe the image.\nConclusion Azure Cognitive Services present a fantastic opportunity to augment your applications with AI capabilities, eliminating the need to build your models or delve into complex AI concepts. These services empower you to enhance your apps with features that perceive, listen, speak, and understand natural language.\nTo learn more about Azure Cognitive Services, I encourage you to visit the official website, explore the documentation, and try the Microsoft Learn modules.\nI hope you found this blog post informative and enjoyable. If you have any questions or feedback, please feel free to comment below. Happy coding! 😊\nI have made a number of example sample codes showing this at work, you’ll need to provide your own Azure Cognitive Service key to get it working, but it all works\nGitHub – BryanAvery/Azure-Cognitive-Services: ## Azure Cognitive Services Examples\n","date":"10 July 2023","externalUrl":null,"permalink":"/azure-cognitive-services/","section":"Articles","summary":"As a developer, you may want to create intelligent applications that can see, hear, speak, and comprehend natural language. You might assume that achieving this requires extensive AI or data science expertise. However, I’m here to inform you that you can incorporate AI capabilities into your applications with just a few lines of code.\n","title":"Azure Cognitive Services","type":"articles"},{"content":"Title: Unlocking the Power of AI: Embracing the Potential for Positive Change\nIntroduction: Artificial Intelligence (AI) is a term often used in various contexts, encompassing machine learning, deep learning, data science, generative AI, and responsible AI. Yet, understanding these concepts and their distinctions is key to unleashing their uplifting potential in solving real-world challenges. In this uplifting blog post, we will shed light on the fundamental concepts of AI technology and explore how they can be harnessed to create positive transformations in businesses and beyond.\nArtificial Intelligence (AI): At its heart, AI represents the remarkable ability of computer programs or machines to mimic human-like behavior. From visual perception to speech recognition, decision-making, and natural language understanding, AI strives to replicate human intelligence. Rather than being a standalone technology, AI is a visionary goal pursued by passionate technologists seeking to unlock unprecedented possibilities.\nGenerative AI: Generative AI, a captivating facet of AI, focuses on the creation of captivating content, spanning images, videos, and text. Known as GenAI, this approach aims to develop AI-generated content that rivals human creations in usefulness and value. Harnessing the power of large language models (LLMs), generative AI enables a diverse range of applications, such as generating insightful follow-up questions after a meeting, bringing textual descriptions to life through images, or even unraveling the humor behind a video’s punchline.\nData Science: Data science emerges as an inspiring and interdisciplinary field that plays a pivotal role in realizing the full potential of AI. By leveraging techniques rooted in machine learning and statistics, data scientists uncover valuable insights and drive informed decision-making from vast troves of data. These visionary professionals lead the charge in solving complex AI problems, employing data-driven approaches to unlock transformative outcomes.\nMachine Learning: Machine learning stands as a powerful tool within the AI landscape, empowering machines to uncover patterns and make predictions through the analysis of vast datasets. With applications extending across the AI spectrum, machine learning algorithms learn from data, recognizing distinguishing features and patterns. The accuracy of predictions improves as the algorithms are exposed to more training data. Consider email spam detection, where algorithms identify specific keywords or suspicious email domains to safeguard inboxes, or credit card fraud detection, which scrutinizes spending patterns and flags irregular transactions to protect users.\nDeep Learning: Deep learning, an awe-inspiring subfield of machine learning, seeks to emulate the intricate workings of the human brain through interconnected artificial neural networks. Unlike traditional machine learning, deep learning autonomously uncovers complex patterns and features in unstructured data, including images, text, and audio. This exceptional approach thrives on copious amounts of data and formidable computing power, enabling transformative applications. For instance, deep learning can be employed to detect cancerous cells in medical images, analyzing each pixel with utmost scrutiny to identify potential indicators of malignancy and classify images accordingly.\nResponsible AI: As AI carries the potential to revolutionize our world, it is vital to embrace the principles of responsible AI development and deployment. Responsible AI upholds the highest ethical standards and ensures accountability, inclusivity, reliability, safety, fairness, transparency, security, and privacy. By steering clear of deceptive practices, such as creating videos that misrepresent individuals’ presence at real-life events, responsible AI safeguards privacy and promotes fairness.\nConclusion: Unleashing the uplifting potential of AI begins with grasping the core concepts that underpin its transformative power. From machine learning and deep learning to generative AI and data science, these remarkable technologies enable machines to learn, interpret data, and reason like never before. Embracing AI responsibly and ethically opens doors to boundless innovation, empowering businesses and individuals to solve complex challenges and propel positive change in the digital age. Let us embrace AI’s profound possibilities, working together to shape a brighter future filled with transformative advancements.\n","date":"7 July 2023","externalUrl":null,"permalink":"/unlocking-the-power-of-ai-embracing-the-potential-for-positive-change/","section":"Articles","summary":"Title: Unlocking the Power of AI: Embracing the Potential for Positive Change\nIntroduction: Artificial Intelligence (AI) is a term often used in various contexts, encompassing machine learning, deep learning, data science, generative AI, and responsible AI. Yet, understanding these concepts and their distinctions is key to unleashing their uplifting potential in solving real-world challenges. In this uplifting blog post, we will shed light on the fundamental concepts of AI technology and explore how they can be harnessed to create positive transformations in businesses and beyond.\n","title":"Unlocking the Power of AI: Embracing the Potential for Positive Change","type":"articles"},{"content":"In today’s interconnected world, Application Programming Interfaces (APIs) have become the backbone of modern software development. They enable seamless communication and interaction between different systems and applications. However, this convenience comes with inherent security risks. To mitigate these risks and ensure the integrity of the entire system, integrating API security into the DevSecOps framework is essential. In this blog post, we will explore the best practices for API security within the context of DevSecOps, focusing on British English conventions.\nAuthentication and Authorisation: To safeguard your APIs, implementing robust authentication and authorisation mechanisms is paramount. Utilise strong authentication methods such as API keys, OAuth, or JSON Web Tokens (JWTs) to ensure that only authorised users or applications can access the API. Additionally, enforce appropriate authorisation controls to restrict access based on user roles and permissions, safeguarding sensitive resources.\nInput Validation and Sanitisation: Defending against common vulnerabilities like injection attacks requires thorough input validation and sanitisation. Implement parameterised queries and leverage input validation libraries to prevent issues such as SQL injection and cross-site scripting. Additionally, use output encoding techniques to ensure the safe transmission of data and minimise the risk of manipulation.\nSecure Communication: Preserving the confidentiality and integrity of data transmitted over APIs demands secure communication protocols. Utilise HTTPS (HTTP over SSL/TLS) to encrypt the data exchanged between clients and the API, protecting against eavesdropping, tampering, and man-in-the-middle attacks. By employing secure communication, you fortify the overall security of your API.\nRate Limiting and Throttling: To prevent abuse, denial-of-service (DoS) attacks, or excessive resource consumption, implement rate limiting and throttling mechanisms. By controlling the number and frequency of API requests from individual clients or IP addresses, you can protect the availability and stability of your API.\nInput and Output Data Validation: Ensuring the integrity of data passing through your API requires comprehensive input and output data validation. Implement robust data validation checks to verify the authenticity and integrity of incoming requests. Additionally, take measures to prevent the inadvertent exposure of sensitive information in API responses, prioritising data privacy and security.\nError Handling and Logging: Efficient error-handling mechanisms play a pivotal role in maintaining the security of your API. Implement effective error messages that provide meaningful feedback to clients without divulging sensitive information. Furthermore, establish proper logging practices to capture relevant security events and anomalies for auditing and monitoring purposes, aiding incident response and analysis.\nSecurity Testing and Code Reviews: Incorporate security testing as an integral part of your DevSecOps pipeline. Conduct regular security scans, vulnerability assessments, and penetration testing to identify and address potential security flaws. Additionally, emphasise code reviews with a focus on secure coding guidelines, promoting a security-first mindset among your development teams.\nSecurity Monitoring and Incident Response: Ensure that your system is equipped with robust monitoring and logging solutions to detect and respond promptly to security incidents. Employ intrusion detection systems (IDS), security information and event management (SIEM) tools, and real-time log analysis to identify suspicious activities. By establishing a comprehensive security monitoring framework, you can proactively address threats and vulnerabilities.\nThird-Party Dependencies: Carefully assess and monitor third-party dependencies, including libraries, frameworks, and APIs, for security vulnerabilities. Keep them up to date with the latest patches and security fixes, as outdated dependencies can expose your API to potential exploitation. Vigilance in managing third-party dependencies contributes to the overall security of your system.\nSecure DevOps Culture: Cultivate a security-conscious culture within your DevOps teams, embedding security practices throughout the software development process.\n","date":"20 June 2023","externalUrl":null,"permalink":"/ensuring-api-security-in-devsecops-best-practices-for-a-robust-system/","section":"Articles","summary":"In today’s interconnected world, Application Programming Interfaces (APIs) have become the backbone of modern software development. They enable seamless communication and interaction between different systems and applications. However, this convenience comes with inherent security risks. To mitigate these risks and ensure the integrity of the entire system, integrating API security into the DevSecOps framework is essential. In this blog post, we will explore the best practices for API security within the context of DevSecOps, focusing on British English conventions.\n","title":"Ensuring API Security in DevSecOps: Best Practices for a Robust System","type":"articles"},{"content":"Have you ever wanted to write a story but felt stuck or uninspired? Or maybe you have a great idea but don’t have the time or skills to turn it into a captivating narrative. If so, you might be interested in Tomb AI, a new online platform that uses artificial intelligence (AI) to help you create stories from scratch.\nWhat is Tomb AI? Tomb AI is an AI-powered storytelling format that lets you generate entire narratives within seconds based on a prompt you type in. You can use Tomb AI to create stories for fun, education, or work and share them with others online.\nTomb AI uses two powerful AI models to generate your stories: GPT-3 and DALL·E 2. GPT-3 is a natural language processing model that can produce coherent and diverse text on any topic. DALL·E 2 is a computer vision model that can create realistic and relevant images from text descriptions.\nHow does Tomb AI work? To use Tomb AI, you must sign up for a free account on their website and choose a template for your story. Templates are pre-made formats that provide structure and guidance for your story, such as fiction, non-fiction, presentation, or outline.\nThen, you type in a prompt for your story, such as a title, a genre, a theme, or a question. For example, you could type “A horror story about a haunted tomb” or “How to make a presentation with Tomb AI”.\nTomb AI will generate a complete story for you within seconds, with intelligent titles, pagination, page layouts, and page text. It will also add AI-generated images from DALL·E 2 to enhance your story visually.\nYou can then edit and customize your story as much as you want by changing the text, the images, the fonts, the colours, and more. You can also add your images or upload files from your device.\nWhen you are happy with your story, you can save it to your library and share it with others via a link or social media. You can also download it as a PDF or print it out.\nWhat are the benefits of using Tomb AI? Tomb AI has many benefits for anyone who wants to create stories with ease and speed. Some of the benefits are:\nIt saves you time and effort by generating stories for you automatically. It sparks your creativity and imagination by giving you new ideas and perspectives. It helps you improve your writing and storytelling skills by providing feedback and suggestions. It makes your stories more engaging and appealing by adding visual elements. It allows you to express yourself and communicate your message effectively. It lets you have fun and enjoy the process of storytelling. How can I get started with Tomb AI? If you are interested in trying out Tomb AI for yourself, you can sign up for a free account on their website: https://tome.app/\nYou will get access to all the features and templates of Tomb AI, as well as unlimited stories and storage. You can also join their community of storytellers and get inspired by other users’ stories.\n","date":"9 June 2023","externalUrl":null,"permalink":"/tomb-ai-a-new-way-to-create-stories-with-artificial-intelligence/","section":"Articles","summary":"Have you ever wanted to write a story but felt stuck or uninspired? Or maybe you have a great idea but don’t have the time or skills to turn it into a captivating narrative. If so, you might be interested in Tomb AI, a new online platform that uses artificial intelligence (AI) to help you create stories from scratch.\n","title":"Tomb AI: A New Way to Create Stories with Artificial Intelligence","type":"articles"},{"content":"Synthetic data is like a virtual twin of real-world information, generated artificially instead of from actual events. It’s created using clever algorithms and serves two primary purposes: validating mathematical models and training machine learning models. You can think of data generated by computer simulations, such as music synthesisers or flight simulators, as synthetic data examples.\nNow, synthetic data plays a crucial role in maximising the responsible and fair use of sensitive information. We’re swimming in an ocean of data about individuals, with details about their unique characteristics, preferences, and behaviours becoming increasingly abundant. As society becomes more data-driven, we’re empowered to gain valuable insights and tackle pressing issues like the climate crisis and the COVID-19 pandemic. Data availability and utilisation are driving research and innovation to new frontiers.\nOf course, with essential data comes great responsibility. When dealing with personal or sensitive data, there are inevitable hurdles to overcome, whether legal, technical, ethical, or practical. That’s where synthetic data comes in handy. It acts as a filter, protecting the confidentiality of certain aspects of the data that should remain private. In many cases, some datasets exist but cannot be released to the general public due to privacy concerns. Synthetic data allows us to sidestep those issues by generating data that mimics the real thing without using actual consumer information without permission or compensation.\nOne of the cool things about synthetic data is its ability to meet specific needs or simulate certain conditions that may not be present in the original data. This is particularly useful when designing systems, as synthetic data provides a simulated or theoretical value, situation, etc. It allows us to account for unexpected results and have a preliminary solution or remedy if things don’t go as planned. Synthetic data often represents authentic data, giving us a baseline.\nMoreover, synthetic data can help us overcome the challenges that real-world data sometimes present. Actual data may be scarce, biased, imbalanced, noisy, or incomplete. Synthetic data can address these issues by augmenting existing datasets and increasing their diversity and representativeness. It can also generate novel scenarios and edge cases that real-world data may miss. Additionally, synthetic data can be instrumental in testing and validating hypotheses and assumptions before applying them to real-world data.\nHowever, it’s important to note that synthetic data is only a magical solution for some data-related problems. There are limitations and risks to consider. For instance, synthetic data may not accurately capture the complexity and variability of real-world data, potentially leading to overfitting or underfitting models. It might introduce biases or errors that don’t exist in real-world data, resulting in inaccurate or misleading outcomes. Moreover, ethical and legal standards that apply to real-world data may not always apply to synthetic data, raising concerns about potential harm or liability. Lastly, not everyone may trust or accept synthetic data, as some stakeholders or users may prefer using real-world data, which could hinder adoption or impact.\nTherefore, using synthetic data with caution and rigour is crucial, following best practices and guidelines for its generation, evaluation, and application. Synthetic data should be clearly labelled and documented to avoid confusion or deception.\nIn conclusion, synthetic data is a powerful tool that allows us to utilise data without compromising privacy. It unlocks new possibilities and opportunities for research and innovation across various domains and sectors. However, we must approach it with care and transparency, acknowledging the challenges and responsibilities that come with its use.\nHere are some example of Synthetic Data\nSynthetic text Synthetic text is artificially-generated text that can be used for various purposes, such as natural language processing, chatbots, text summarization, sentiment analysis, etc. Synthetic text can be generated using different methods, such as rule-based systems, statistical models or neural networks1.\nFor example, Amazon is using synthetic data to train Alexa’s language system. By generating synthetic utterances based on real user queries, Amazon can improve Alexa’s understanding and response capabilities1.\nSynthetic media Synthetic media refers to video, image or sound that is artificially created or manipulated using algorithms. Synthetic media can be used for computer vision, face recognition, speech synthesis, animation, gaming, etc. Synthetic media can be generated using different methods, such as computer graphics, generative adversarial networks or deepfakes1.\nFor example, Google’s Waymo uses synthetic data to train its self-driving cars. By generating synthetic scenarios and environments based on real-world data, Waymo can improve its perception and decision-making systems1.\nSynthetic tabular data Synthetic tabular data refers to structured data that is artificially generated to mimic real-world data. Synthetic tabular data can be used for data analysis, machine learning, testing, privacy preservation, etc. Synthetic tabular data can be generated using different methods, such as sampling, perturbation or simulation.\nFor example, health insurance company Anthem works with Google Cloud to generate synthetic data for healthcare research. By generating synthetic patient records based on real-world data, Anthem can enable researchers to access and analyse data without compromising privacy.\n","date":"11 May 2023","externalUrl":null,"permalink":"/exploring-the-power-and-considerations-of-synthetic-data/","section":"Articles","summary":"Synthetic data is like a virtual twin of real-world information, generated artificially instead of from actual events. It’s created using clever algorithms and serves two primary purposes: validating mathematical models and training machine learning models. You can think of data generated by computer simulations, such as music synthesisers or flight simulators, as synthetic data examples.\n","title":"Exploring the Power and Considerations of Synthetic Data","type":"articles"},{"content":"","date":"11 May 2023","externalUrl":null,"permalink":"/categories/synthetic-data/","section":"Categories","summary":"","title":"Synthetic Data","type":"categories"},{"content":"AI-generated images have become increasingly popular in recent years, as they offer a quick and easy way to create unique and eye-catching visuals. There are several websites that offer AI-generated images, each with its own set of features and capabilities.\nDall-E is a groundbreaking AI image generator developed by OpenAI, the same team that created the GPT language models. Dall-E is capable of generating high-quality, unique images from textual descriptions, making it a powerful tool for artists, designers, and anyone who needs to create visuals quickly and efficiently.\nUnlike other AI image generators, which are typically trained on large datasets of images, Dall-E was trained on textual descriptions, allowing it to generate images from scratch based solely on a text input. For example, if you provide Dall-E with the prompt “a cat made of sushi”, it will generate an image of a cat made entirely out of sushi.\nDall-E has already been used to create a wide range of images, from surreal and abstract art to more realistic depictions of everyday objects and scenes. Its ability to generate unique and creative images based on textual descriptions has the potential to revolutionize the way we create and think about visual content.\nHowever, like many AI tools, Dall-E is not perfect and there are still limitations to what it can do. For example, generating high-quality, detailed images can be time-consuming and resource-intensive, and the output may not always match the intended prompt. Nonetheless, Dall-E represents a major step forward in the field of AI-generated images and has the potential to transform the way we create and consume visual content.\nSome websites, such as Deep Dream Generator and Artbreeder, allow you to generate and customize images using pre-trained models. These websites offer a range of customization options and styles, making them a great option for those who want to create unique images without having to train their own models.\nOther websites, such as RunwayML and Ganbreeder, allow you to train your own models to generate customized images. These websites require some coding knowledge and can be resource-intensive, but they offer greater control over the final output.\nThere are also websites that specialize in specific types of AI-generated images, such as ThisPersonDoesNotExist, which generates realistic human faces, and NeuralStyle.art and Pikazo, which allow you to apply the style of one image to another.\nOverall, AI-generated images offer a quick and easy way to create unique and eye-catching visuals. By exploring the different websites and tools available, you can find the one that best fits your needs and create stunning AI-generated images in no time.\nDeep Dream Generator – https://deepdreamgenerator.com/ Artbreeder – https://www.artbreeder.com/ RunwayML – https://runwayml.com/ Ganbreeder – https://ganbreeder.app/ ThisPersonDoesNotExist – https://thispersondoesnotexist.com/ AI Painter – https://www.ai-art.tokyo/en/ NeuralStyle.art – https://neuralstyle.art/ Artisto – https://artisto.net/ Prisma – https://prisma-ai.com/ Pikazo – https://pikazoapp.com/ Leonardo – https://app.leonardo.ai/ai-generations Each of these websites offers a different set of features and capabilities, so it’s worth exploring each one to see which one best fits your needs.\nHere’s a table summarizing the pros and cons of each of the AI Images websites:\nWebsite Pros Cons Deep Dream Generator Offers a range of image editing tools and filters. The free version has limited functionality and resolution. Allows you to upload your own images to apply the AI-generated effects. The premium version can be expensive for some users. Artbreeder Allows you to generate and combine images of different styles and genres. The interface can be overwhelming for some users. Has a large library of images to work with. The generated images can sometimes be low-resolution or low-quality. Offers a wide range of customization options. RunwayML Allows you to use a wide range of pre-trained models for generating images. Requires some coding knowledge to use effectively. Has a simple and user-friendly interface. Some models may require significant computing power. Offers a community of developers and users who can provide support and guidance. Ganbreeder Offers a unique interface for combining and evolving images. The generated images can sometimes be low-resolution or low-quality. Has a large library of images to work with. The interface can be overwhelming for some users. Allows you to customize the evolution parameters. ThisPersonDoesNotExist Generates realistic human faces that can be used for a range of applications. Can only generate human faces. Offers a simple and easy-to-use interface. The generated faces can sometimes appear “uncanny” or unsettling. AI Painter Offers a range of image styles to work with, including famous artists and art styles. The generated images can sometimes be low-resolution or low-quality. Allows you to upload your own images to apply the AI-generated effects. The interface can be overwhelming for some users. Offers a range of customization options. NeuralStyle.art Allows you to apply the style of one image to another. Requires some knowledge of machine learning concepts to use effectively. Offers a range of pre-defined styles to work with. Can be slow and resource-intensive. The generated images are high-quality and high-resolution. Artisto Offers a range of pre-defined image styles to work with. The generated images can sometimes be low-resolution or low-quality. Allows you to upload your own images to apply the AI-generated effects. The interface can be overwhelming for some users. Offers a range of customization options. Prisma Offers a range of pre-defined image styles to work with. The generated images can sometimes be low-resolution or low-quality. Allows you to upload your own images to apply the AI-generated effects. The free version has limited functionality. Offers a range of customization options. Pikazo Allows you to apply the style of one image to another. Requires some knowledge of machine learning concepts to use effectively. Offers a range of pre-defined styles to work with. Can be slow. The generated images are high-quality and ","date":"28 April 2023","externalUrl":null,"permalink":"/ai-images/","section":"Articles","summary":"AI-generated images have become increasingly popular in recent years, as they offer a quick and easy way to create unique and eye-catching visuals. There are several websites that offer AI-generated images, each with its own set of features and capabilities.\n","title":"AI Images","type":"articles"},{"content":"Hey, here’s a roundup of all the ChatGPT versions we’ve got till now. Let’s keep this list fresh and handy, alright?\nHuggingChat HuggingChat is an open-source AI assistant developed by Hugging Face that aims to provide users with a friendly, human-like personality and the ability to understand and respond to natural language queries1. It is essentially a user interface that allows people to interact with an open-source chat assistant dubbed Open Assistant1. With HuggingChat, you can enjoy an AI assistant that is accessible to everyone and can handle many of the tasks that ChatGPT can.\nImages AI Images.ai is a website that offers an AI-powered image generator called Imagen AI. Imagen AI can generate unlimited variations from a single photo and can generate a similar version of an existing photo or design. It can keep the look, feel, and colour pattern of your seed image and generate look-alike images that can be replacements for the originals for A/B testing, Ad refreshment and more.\nWord AI Have you ever spent hours staring at a blank page, struggling to come up with fresh and engaging content for your website, blog, or social media? As a writer, it can be frustrating to constantly come up with new ideas and phrases to keep your readers interested.\nBut what if there was a way to generate high-quality, unique content in just a few clicks? Enter Word AI, a website that offers an AI text rewriter service that can help you create more captivating content in no time.\nUsing advanced machine learning models, Word AI can completely restructure your sentences while keeping the same overall meaning. It can also add more details and information to your text to make it more informative and interesting. Plus, it can describe the same ideas differently by using synonyms, paraphrasing, and reordering to help you avoid sounding repetitive.\nBut Word AI isn’t just a synonym generator. It can also improve the quality of your text by fixing grammar, spelling, punctuation, and style errors. It can even improve the clarity of your text by removing ambiguity, redundancy, and vagueness.\nIf you’re worried about your content sounding too robotic or formulaic, Word AI allows you to adjust how creative it is by making it more conservative or more adventurous. And with the ability to generate up to 1,000 rewrites per original article, you can get the most value out of each piece of content.\nWord AI also supports HTML content and has an API for integrating with other applications. And with plans starting at just $49.95 per month, it’s an affordable solution for anyone looking to streamline their content creation process.\nSo if you’re tired of staring at a blank page and want to create more unique and engaging content, give Word AI a try. You can even test it out for free for three days to see how it can transform your writing.\nEleven labs – Voice cloning Eleven Labs is a startup that offers a voice generation service based on artificial intelligence. It claims to provide the most realistic and versatile AI speech software ever. Eleven Labs can create high-quality spoken audio in any voice and style, with human-like intonation and inflection. It can also clone voices from samples or design new synthetic voices from scratch. Eleven Labs can help creators and publishers produce engaging and dynamic audio content for storytelling, news articles, newsletters, blogs, audiobooks, and more. Eleven Labs also has a feature called Projects, which will allow users to direct and edit narration with full control over the creative process. Eleven Labs is committed to ethical AI and implements safeguards to minimize the risk of harmful abuse. You can try Eleven Labs for free for three days or subscribe to one of its plans starting from $49 per month.\n","date":"27 April 2023","externalUrl":null,"permalink":"/various-chatgpt-implementation/","section":"Articles","summary":"Hey, here’s a roundup of all the ChatGPT versions we’ve got till now. Let’s keep this list fresh and handy, alright?\nHuggingChat HuggingChat is an open-source AI assistant developed by Hugging Face that aims to provide users with a friendly, human-like personality and the ability to understand and respond to natural language queries1. It is essentially a user interface that allows people to interact with an open-source chat assistant dubbed Open Assistant1. With HuggingChat, you can enjoy an AI assistant that is accessible to everyone and can handle many of the tasks that ChatGPT can.\n","title":"Various ChatGPT implementation","type":"articles"},{"content":" Chatbots have been around for a while and are widely used to automate customer service and support. However, with the advent of advanced language models like ChatGPT, the capabilities of chatbots have significantly expanded.\nChatGPT is a language model developed by OpenAI that’s based on the GPT-3 architecture. It’s a Generative Pre-trained Transformer that uses deep learning algorithms to generate human-like text. With massive data and advanced training techniques, ChatGPT can understand and respond to a wide range of topics with remarkable accuracy.\nHere are a few websites that showcase the capabilities of ChatGPT and how it works:\nOpenAI’s API Demo: OpenAI provides a demo of its API that allows you to test ChatGPT’s abilities. The demo includes a text box to type in a prompt and see the model’s response. The demo provides a good idea of ChatGPT’s abilities and how it can be used to generate text. Replika: Replika is a personal AI companion that uses ChatGPT to understand and respond to users. The chatbot can answer questions, converse, and even provide emotional support. Replika offers an excellent example of how ChatGPT can create chatbots that can understand and respond to various topics. AI Dungeon: AI Dungeon is a text-based adventure game that uses ChatGPT to generate stories based on the player’s inputs. The game provides an excellent example of how ChatGPT can create text creatively and engagingly. Talk to Transformer: Talk to Transformer is a website that demos ChatGPT’s abilities. The website lets you type in a prompt and see the model’s response. The website provides a good idea of ChatGPT’s abilities and how it can be used to generate text. In conclusion, ChatGPT represents a significant advancement in language modelling. With its ability to understand and respond to a wide range of topics with remarkable accuracy, ChatGPT has the potential to revolutionize the field of chatbots and AI-powered text generation. The websites mentioned above provide a good idea of the capabilities of ChatGPT and how it can be used in various applications.\n","date":"27 April 2023","externalUrl":null,"permalink":"/chatgpt-the-advancements-in-language-modelling/","section":"Articles","summary":" Chatbots have been around for a while and are widely used to automate customer service and support. However, with the advent of advanced language models like ChatGPT, the capabilities of chatbots have significantly expanded.\nChatGPT is a language model developed by OpenAI that’s based on the GPT-3 architecture. It’s a Generative Pre-trained Transformer that uses deep learning algorithms to generate human-like text. With massive data and advanced training techniques, ChatGPT can understand and respond to a wide range of topics with remarkable accuracy.\n","title":"ChatGPT: The Advancements in Language Modelling","type":"articles"},{"content":"This post shows how each provider measures up and helps you select the correct Software Composition Analysis for your needs.\nFact: Software Composition Analysis (SCA) protects the software supply chain. In a report by Forrester[1] and Gartner[2], they explore how industry providers measure up, which will assist you in selecting the right one for your needs. It’s a valuable assessment of top suppliers in today’s market. Details below are an extract of this report with additional information which applies to our environment.\nDevelopers face the test of rapidly making separated, modified, and convincing client encounters. Accordingly, they never again compose their code to handle each issue. They gather, design, and computerise their code and regularly depend on typical open source and business parts to rapidly add application usefulness. Open-source use has detonated, with the expected level of open-source in reviewed codebases [3]expanding from 36% in 2015[4] to 75% in 2020[5]. Tragically, as firms progressively depend on outside parts, they uncover themselves and their clients to more severe danger when they incorporate fundamental weaknesses or don’t adjust to organisational strategies. Moreover, late episodes like the SolarWinds break exhibit the risks of nasty libraries in programming and the requirement for more prominent straightforwardness in the product store network.\nAs a result of these trends, you should look for providers that:\n[1] https://reprints2.forrester.com/#/assets/2/425/RES176091/report\n[2] https://www.gartner.com/doc/reprints?id=1-26OO2IJ6\u0026amp;ct=210630\u0026amp;st=sb\n[3] Forrester Software Composition Analysis report\n[5] https://www.synopsys.com/software-integrity/resources/analyst-reports/open-source-security-risk-analysis.html\n● Address changes in a broad scope of non-proprietary parts. It does not just concern conventional open-source code. The items might incorporate both open source and outsider or shut source libraries – in the scope of programming dialects and systems. We might approach the source code, or we might be depending on parallel relics. More than source code, dev groups influence compartments, Kubernetes, serverless capacities, and framework as-code (IaC) layouts to build their applications. Search for SCA devices that can filter every one of the non-proprietary parts in our application and give a brought-together perspective on dangers and remediations.\n● Encourage designers on how to remediate weaknesses, permit chances, and old code. Auto remediation elements can further develop proficiency, yet designers have been delayed in acknowledging them in light of fears that a contradictory fix could break the form. SCA arrangements should simplify remediation and be safe; look for sellers that expand suggested fixes with an appraisal of the fix’s danger so designers know what to computerise and what to examine further. Moreover, think about past weaknesses and authorising fixes and ask your seller how they can assist you with staying up with the latest or be cautioned of ineffectively keeping up with parts that could become a burden.\n● Investigate and reinforce the product store network. By distinguishing high-hazard parts, SCA has consistently assumed a role in ensuring the product store network; however, top SCA sellers have increased their game. Presently, banner reliance disarrays dangers or eliminates malignant parts from vaults. The recent US Cybersecurity Executive Order[1] will uphold more prominent straightforwardness by requiring those offering to the public authority to produce and share a product bill of materials (SBOM). A couple of SCA suppliers create SBOMs in SPDX or CycloneDx organisations, and others intend to follow accordingly.\nThis assessment features Leaders, Strong Performers, Contenders, and Challengers. It’s an appraisal of the top sellers on the lookout and doesn’t address the whole scene.\nVendors\nWe have included 10 vendors in this assessment: Checkmarx, FOSSA, GitLab, JFrog, Revenera, Snyk, Sonatype, Synopsys, Veracode, and WhiteSource\nWe will be looking at the three leading solutions, based on their results, being the market leaders and strong offerings, these include:\nSynopsys Sonatype WhiteSource Snyk Synopsys[1]\nSynopsys comes as the strongest of all the Software Composition Analysis tools, based on an evaluation of Black Duck, Synopsys software composition analysis (SCA) solution.\nAmong the 10 SCA providers evaluated, Synopsys received: The highest score in the Strategy category The second highest score in the Market Presence category Among the highest scores in the Vulnerability Identification criterion The highest possible score in the Revenue criterion The highest possible score in the Product Vision criterion The highest possible score in the Market Approach criterion The highest possible score in the Corporate Culture criterion This was to be the strongest contender; however, the offering does not support an Air Gapped solution therefore to have two different SCA in the official and secret environment would not be practical, so this has been rejected on this basis.\nSonatype[2]\nSonatype’s Nexus platform was recognised as a leader with the highest score in the market presence category amongst all companies evaluated.\nThe report notes:\n“Policy is an area of strength for Sonatype, with out-of-the-box policies that align to a range of standards (particularly in the IaC pack) and a policy engine that allows users to create and assign policies to certain types of applications.”\nCore to whom Sonatype is giving organisations control of their code and the code that makes it into production applications. Across the Nexus platform, you can create custom security, licence, and architectural policies based on application type or organisation and contextually enforce those policies across every stage of the software development life cycle.\nTheir policy management is only as good as their data. Precision matters. They pride themselves on having the most expansive, most in-depth, and most actionable database of open-source components and vulnerabilities. They examine fingerprints–not just file names and package manifests–to precisely identify risk with Advanced Binary Fingerprints (ABF). It’s this precision that lets them promise low false positives and negatives.\nThe finding and details\nData from Gartner[3]\nData flow for updating a disconnected environment\nSonatype provides tooling to aid with obtaining and applying data updates in Disconnected Environments.\nThe flow of data is as follows.\nCustomer will run a Sonatype provided tool on a customer provided server 2 that is connected to the Internet (i.e. outside the Disconnected Environment). This tool will download the requested update files from a secured AWS S3 Bucket 1 over HTTPS using credentials provided to the Customer by Sonatype. The Customer will transfer the downloaded data via a means of their choosing from their server 2 to a Customer Staging Server 3 inside the Disconnected Environment. The Customer will run tools provided by Sonatype on the Staging Server 3 to apply the downloaded updates to the offline databases 4. WhiteSource[4]\nWhiteSource being around since 2002 with its open-source manual scanner makes it a long-time master at SCA.\nOver the years, it has matured, the first open-source management solution in 2011, including continuous automated detection in 2014. Scanning for security vulnerability prioritisation in 2017 and now with auto-remediation of security vulnerabilities.\nThis being a strong contender in the selection process.\nWhiteSource Connected WhiteSource Air Gapped Evaluation \u0026amp; Contracting Integration and Deployment 9 Complexity 5 Not Available Data Volume (GB) Frequency vulnerable data real time Service and Support 9 Not Available Product Capabilities 8 Not Available Execution location Not Available Information type outbound Information type inbound Communication inbound (Source) Communication outbound (Destination) Data from Gartner[5]\nThis was the market leader; however, the offering does not support an Air Gapped solution therefore to have two different SCA in the official and secret environment would not be practical, so this has been rejected on this basis.\nSynk[6]\nSnyk tests for vulnerabilities in your own code, open source dependencies, container images and infrastructure as code configurations, and offers context, prioritisation, and remediation.\nFully support for Open Shift, giving it a good solution for our needs.\nThe offering from Synk does not support an Air Gapped solution therefore to have two different SCA in the official and secret environment would not be practical, so this has been rejected on this basis.\nSnyk Connected Snyk Air Gapped Evaluation \u0026amp; Contracting 8 N/A Integration and Deployment 10 N/A Complexity N/A Data Volume (GB) N/A Frequency vulnerable data real time N/A Service and Support 6 N/A Product Capabilities 8 N/A Execution location Remote N/A Information type outbound Only Open Source code only[7] N/A Information type inbound Report findings N/A Communication inbound (Source) unknown N/A Communication outbound (Destination) unknown N/A Decision\nOne of the big deciding factors of the SCA tooling is about working in an Air Gapped environment, and several of the leading options are not able to provide this solution.\nThe economics of having an air gapped solutions is unviable, also the manpower efforts and each environment would require its own licensing\nTherefore, it is recommended to have one Internet connected solution and one Air Gapped solution that all applications pass through the SCA pipeline for qualification checking in whichever environment it will be hosted in.\nWith all solutions data is sent to the supplier, even though this is a fingerprint of the Open Source detailing which packages have been used for any given solution, it still represents which Open Source packages are being used and could be a point of vulnerability.\nIn order of valued importance and functionality the bases on this work the following has been decided:\nSonatype Synopsys WhiteSource Synk Decision Consequences We feel that the best product has been chosen based on our needs and requirements, along with the industry independent reviews.\n[1] https://www.synopsys.com/software-integrity/resources/analyst-reports/forrester-wave-software-composition-analysis.html\n[2] https://blog.sonatype.com/forrester-recognition-market-leader-in-software-composition-analysis\n[3] https://www.gartner.com/reviews/market/software-composition-analysis-sca/vendor/sonatype/product/nexus-lifecycle\n[4] https://www.whitesourcesoftware.com/resources/blog/software-composition-analysis/\n[5] https://www.gartner.com/reviews/market/software-composition-analysis-sca/vendor/whitesource/product/whitesource\n[6] https://snyk.io/\n[7] https://docs.snyk.io/more-info/how-snyk-handles-your-data#common-data-types\n","date":"13 April 2023","externalUrl":null,"permalink":"/software-composition-analysis-tools/","section":"Articles","summary":"This post shows how each provider measures up and helps you select the correct Software Composition Analysis for your needs.\nFact: Software Composition Analysis (SCA) protects the software supply chain. In a report by Forrester[1] and Gartner[2], they explore how industry providers measure up, which will assist you in selecting the right one for your needs. It’s a valuable assessment of top suppliers in today’s market. Details below are an extract of this report with additional information which applies to our environment.\n","title":"Software Composition Analysis Tools","type":"articles"},{"content":"Here is a list of Security Policies and Guidelines from Microsoft\nFor V01: https://learn.microsoft.com/en-us/azure/storage/blobs/security-recommendations#:~:text=Require%20secure%20transfer%20(HTTPS)%20to%20the%20storage%20account\nFor V02: https://learn.microsoft.com/en-us/azure/app-service/security-recommendations#:~:text=Use%20static%20IP%20restrictions\nFor V03: No Microsoft recommendation applies here\nFor V04: https://learn.microsoft.com/en-us/security/benchmark/azure/baselines/service-bus-security-baseline#dp-3-encrypt-sensitive-data-in-transit\nFor V05: https://learn.microsoft.com/en-us/azure/network-watcher/network-watcher-nsg-flow-logging-overview#best-practices\nFor V06: https://learn.microsoft.com/en-us/azure/network-watcher/network-watcher-nsg-flow-logging-overview#best-practices\nFor V07: https://learn.microsoft.com/en-us/azure/storage/blobs/security-recommendations#networking:~:text=Enable%20firewall%20rules and https://learn.microsoft.com/en-us/azure/key-vault/general/best-practices#:~:text=Turn%20on%20firewall%20and%20virtual%20network%20service%20endpoints.\nFor V08: https://learn.microsoft.com/en-us/azure/storage/blobs/security-recommendations#:~:text=Turn%20on%20soft%20delete%20for%20blobs\n","date":"5 April 2023","externalUrl":null,"permalink":"/security-policies-and-guidelines/","section":"Articles","summary":"Here is a list of Security Policies and Guidelines from Microsoft\nFor V01: https://learn.microsoft.com/en-us/azure/storage/blobs/security-recommendations#:~:text=Require%20secure%20transfer%20(HTTPS)%20to%20the%20storage%20account\nFor V02: https://learn.microsoft.com/en-us/azure/app-service/security-recommendations#:~:text=Use%20static%20IP%20restrictions\nFor V03: No Microsoft recommendation applies here\nFor V04: https://learn.microsoft.com/en-us/security/benchmark/azure/baselines/service-bus-security-baseline#dp-3-encrypt-sensitive-data-in-transit\nFor V05: https://learn.microsoft.com/en-us/azure/network-watcher/network-watcher-nsg-flow-logging-overview#best-practices\nFor V06: https://learn.microsoft.com/en-us/azure/network-watcher/network-watcher-nsg-flow-logging-overview#best-practices\nFor V07: https://learn.microsoft.com/en-us/azure/storage/blobs/security-recommendations#networking:~:text=Enable%20firewall%20rules and https://learn.microsoft.com/en-us/azure/key-vault/general/best-practices#:~:text=Turn%20on%20firewall%20and%20virtual%20network%20service%20endpoints.\nFor V08: https://learn.microsoft.com/en-us/azure/storage/blobs/security-recommendations#:~:text=Turn%20on%20soft%20delete%20for%20blobs\n","title":"Security Policies and Guidelines","type":"articles"},{"content":"Sensitive information can be protected from misuse through Encryption, Pseudonymization and Anonymization controls, converting plain text to an unusable format.\nOnly authorized users with the proper key/source should be able to see sensitive data (or in the case of Anonymization, not at all). Each of these methods work differently, as summarized below.\n","date":"24 November 2022","externalUrl":null,"permalink":"/sensitive-information-definitions/","section":"Articles","summary":"Sensitive information can be protected from misuse through Encryption, Pseudonymization and Anonymization controls, converting plain text to an unusable format.\nOnly authorized users with the proper key/source should be able to see sensitive data (or in the case of Anonymization, not at all). Each of these methods work differently, as summarized below.\n","title":"Sensitive information definitions","type":"articles"},{"content":"There are various types and nature of data we store in Azure storage. All kinds of blob data have different accessibility requirements. Sometimes data accessibility reduces over time, whereas accessibility remains the same for some blob data types. There is no point in paying the same price for data that is rarely being accessed or not accessed at all. Azure provides Access Tiers property to address such scenarios and optimize the cost on blobs with less accessibility.\nAzure storage offers standard and premium options to create a storage account from a performance standpoint. If you choose the standard option (GPv2 storage) while making a storage account, this option will allow you to leverage three access tiers, i.e., Hot, Cool, and Archive, for a blob object. The Premium storage option doesn’t allow these options, and it is by default created with preconfigured access tier, which offers better performance and accessibility than the hot tier of the standard storage option. We can choose an appropriate access tier based on the frequency and nature of data accessibility.\nWe can only use two access tier options at the Azure storage account level, whereas all three access tier options can be used at the blob object level. If we upload any blob object to a storage account container, it inherits access tiers from the default access tier setting of the storage account in case you will not specify it for that blob. You can identify any blob object whether it is using an inherited default access tier or if its access tier has been modified. If a blob object has an access tier set with the word Inferred along with its access tier option like Hot (Inferred) or cool (Inferred), it means this setting is inherited from the default access tier of the storage account. If we change the access tier of the Azure storage account, then a new access tier will apply to all blobs using the inherited access tier having the inferred option.\nHot tier You should use the hot tier if you need frequent data accessibility (read, write operations) with low latency. Most of the transactional workload uses this tier to get optimal performance. This tier will charge you the highest storage cost and lowest access cost among all three tiers.\nCool tier This tier is suitable for infrequent data access requirements. It also gives good performance and durability. The pricing for this tier is lower than the hot tier for storage cost and higher than the hot tier for access cost. This tier is ideal for backups, DR, or unstructured data that are not frequently used. The minimum retention to store data in this tier is 30 days.\nArchive tier This tier is priced lowest for storage cost and highest for access cost among all three access tiers. This is suitable for blob data you occasionally use, like long-term backup retentions or any data you want to preserve that will not be used for longer. The data stored in this tier is in offline mode and cannot be read and modified. You need to rehydrate the data if you want to use it. The rehydration process may time a lot of time to serve you the actual data, so the performance is deficient in this tier. You can store data in achieve tier starting from 180 days onwards.\nThere are some limitations as well in the Archive tier. It does not support all types of redundancy options like Hot and Cool tiers. It does not support Zone-redundant storage (ZRS), Geo-zone-redundant storage (GZRS), and Read-Access Geo-Zone redundant storage (RA-GZRS). There is also one constraint in migrating redundant options from LRS to GRS; you can move to GRS if updates are done within the last 30 days, and you have not moved any blob to GRS since it was configured to LRS redundancy.\nWe can set an access tier while creating the Azure storage account and change it later after its creation. We have only two options, Hot and Cool access tiers at the account level. In contrast, the Archive access tier can be set only at the blob or object level, which I demonstrated in this article’s second last image. If you upload any blob to a container, it inherits the access tier from its respective storage account in case you explicitly do not change it during upload. Later we can change the access tier of any object or blob as per our requirement. Changing the access tier from hot to cold to achieve will charge you for reading and writing operations.\n","date":"13 July 2022","externalUrl":null,"permalink":"/azure-access-tiers-in-azure-storage/","section":"Articles","summary":"There are various types and nature of data we store in Azure storage. All kinds of blob data have different accessibility requirements. Sometimes data accessibility reduces over time, whereas accessibility remains the same for some blob data types. There is no point in paying the same price for data that is rarely being accessed or not accessed at all. Azure provides Access Tiers property to address such scenarios and optimize the cost on blobs with less accessibility.\n","title":"Azure Access Tiers in Azure storage","type":"articles"},{"content":"","date":"13 July 2022","externalUrl":null,"permalink":"/categories/blob/","section":"Categories","summary":"","title":"BLOB","type":"categories"},{"content":"Overview Businesses should believe that every team is in the business of creating great customer experiences.\nTo achieve that, the application must do more than just provide control, reporting and audibility. The business needs to tap into data signals from across its business and use them to drive ongoing improvements in the products, services, and experiences they intend to deliver to its customers.\nData-first cloud strategy The opportunity contained in the shift from reactive to predictive— knowing that the car is on its way to failure before it fails—is hard to overstate. For the business and for the customers, every product, service, and business process is ripe for reinvention. The business has invested in applications, an application platform, and an infrastructure platform spanning from enterprise and independent software vendor (ISV) developers to citizen developers. The entire business cloud comes together as a unified digital-transformation platform with consistent security, identity, and compliance boundaries.\nIntroduction Defining the environment strategy is one of the most important steps in the implementation of the application.\nEnvironment-related decisions affect every aspect of the application, from application lifecycle management (ALM) to deployment and compliance. At a fundamental level, a good environment strategy is about obtaining the right balance with multiple layers of compliance and security, productivity, collaboration, isolation, performance, and maintainability. A strategy to manage environment provisioning and access, and controlling resources within them, is key to\nSecuring data and resource access Organizing and structuring solution components Governing and managing capacity Environment strategy Environments are containers that store, manage, and share our data. They also store the data model, application metadata, process definitions, and security constructs to control access to data and applications. A successful environment strategy defines the core principles and policies for creating, granting access to, and decommissioning environments of different types, along with the necessary governance process.\nThe project plan plays a crucial role in defining the environment strategy. Some activities could run in parallel, for example, training and data migration, as long as there are enough environments available. Constraints such as timeline and cost need to be considered as well.\nTo get started with creating the environment strategy, I’d like to ask the following questions:\nWhere are my users physically located? What are business data compliance and residency requirements? What types of environments are required, and when? What are the different roles (such as developers, testers, admins, business analysts and trainers), and which environments do they need access to? Do we have overlapping activities in the project plan that will require an environment (such as training, testing, and data migration)? Is there enough time allocated in the plan for preparing an environment for a specific use (such as refresh and restore operations before training)? What’s the access procedure for an environment? Which apps will be installed in the environment? Will the solution require more than one production environment? Which services and third-party applications do I need to integrate with? It should be apparent from these questions that the environment strategy is not the responsibility of a single person or team. It can involve IT admins, the architects responsible for the design and implementation of the solution, the information security and compliance teams, and the business stakeholders. Environment-related decisions are hard and expensive to change. The environment strategy affects how solutions are implemented.\nEnvironment planning? Environment planning is the process of describing the details of all the environments required during and after implementation. It includes procuring and preparing all environments that the team will need to adequately develop and test the application solution. The environment plan is a matrix format that lists the type, topology, deployment option, and due date for each environment. This plan is a living document that should be revisited after each milestone of the project.\nKey factors affected by an environment strategy The key factors directly affected by an environment strategy, include security and compliance, ALM, operations, and functional and non-functional aspects of the solution.\nCompliance Security and compliance are critical considerations for our environment strategy. We need to ensure that data is stored and processed in accordance with local or regional laws, such as data residency requirements for a specific region.\nThe most common elements affecting compliance are:\nThe physical location of the environment(s), which usually determines data residency The specific features and apps in the scope and their data processing requirements The encryption (at rest and in transit for confidential information) The disaster recovery procedures to restore the service and data The data retention policies, and the ability to back up and restore data The personally identifiable information (PII) standards for data protection, and ensuring the service is compliant with the regulatory requirements for the industry and region Performance and scalability Cloud services provide a high degree of scalability and performance. Based on considerations such as network latency, firewalls, network traffic monitoring, organisational proxies, and routing by the internet service provider (ISP), globally distributed users can experience higher latencies when accessing the cloud.\nEnvironment Location User Location Device Network Latency Bandwidth London London Browser Corporate network 80ms 6 Mbs Internet This exercise gives a fair idea of how the network latency will affect the user experience based on the location of application environment in use. This information can be used to make a balanced choice so most users have an acceptable level of latency, and application design can be optimised for users in high-latency locations.\nThe environment types should be chosen carefully, based on the workload and the capacity needed. Using trial or low tier sandbox environments, for example, will not deliver the same level of performance as live production environments, so it may not be suitable to develop or test the solution on a trial or low tier sandboxes.\nThe scalability of the SaaS platform is a critical consideration for the application. The scalability parameters for a SaaS could be:\nHow many parallel connections or concurrent users can you support with the application or in a single environment? How many API calls is a user entitled to make? What are the limits on workflow or code executions? What is the peak transaction volume per hour? What is the imported transactions volume during the peak hour? The following is a perspective of the SaaS cloud interpretation for scale-up/ vertical and scale-out/ horizontal scalability for the application.\nMaintainability Maintainability measures the ease and speed of maintaining the application, including service updates, bug fixes, and rolling out change requests and new functionality. If you have several applications sharing common components in the same environment, we should consider maintainability when upgrading or deploying a new release. It’s also important to invest in automation testing so you can run regression tests and quickly identify any dependencies that could cause issues. The effort to maintain the solution is directly proportional to the number of environments involved.\nALM ALM includes the tools and processes that manage the solution’s lifecycle and can affect the long-term success of a solution. When following the ALM of a solution, consider the entire lifespan of the solution, along with maintainability and future-proofing. Changes to our environment strategy will directly affect the ALM (and vice versa), but it’s important to be clear that environments are not the repository of your code and customizations. Environments can be used to separate business functions or for different purposes, such as development, testing, and production. Typically, at least three environments are necessary to support a mature release-management process.\nTypes of Enviroements Production environments are meant to support the business. By default, production environments are more protected for operations that can cause disruption, such as copy and restore operations. Sandbox environments can be used to develop, test, and delete as required.\nThe effort to maintain the solution is directly proportional to the number of environments involved.\nPurposes of environments Development One or more development environments are usually required, depending on the customisation requirements and time available. Development environments should be set up with proper DevSecOps to allow for smooth CI/CD. Quality assurance (QA) Allows for solution testing from both a functionality and deployment perspective before the solutions are given to the business teams in a user acceptance testing (UAT) environment. Only managed solutions should be deployed here. Depending on project requirements, there can be multiple testing environments, including regression testing, performance testing, and data migration testing. UAT is Generally the first environment that business users will have access to. It will allow them to perform UAT testing before signing off a deployment to the production environment for going live. Training Utilised to deliver training. It allows business users to practice in a simulated environment without the risk of interfering with live data. Pre-Production An environment allowing for final customer sign off before deployment of the latest version to Production Production The live system for business users. Future-proofing Future-proofing is the process of developing methods to minimize any potential negative effects in the future. It can also be referred to as resilience of the solution to future events. The environment strategy needs to take into consideration any future phases and rollouts of the solution and allow us to deal with changing requirements and build a solution that will not limit the business or take away necessary control.\nEnvironments and project complexity When you buy the PEGA, you get three environments. One is the production environment, which is where the business will be conducted. It’s a robust environment, with high availability (HA) and disaster recovery (DR) capabilities. In addition to the production environment, we will receive one sandbox environment that’s a standard acceptance testing (tier 2) instance for the life of the tenant. It’s a nonproduction, multi-box instance that can be used for testing, UAT, integration, and training needs. (Because it’s a basic tier 2 instance, it may not be enough for every type of testing. For example, performance testing needs a bigger instance to handle larger data volumes and more users.) Depending on the project complexity, these environments may not be sufficient. The Figure below depicts a chart comparing the additional requirements of the application.\nEnvironment purpose Finance and Operations Dataverse Standard subscription Less complex project More complex project Production Large Production Pre-Production Large Production Training Small Sandbox MAT Standard Sandbox UAT Standard Sandbox E2E Standard Sandbox System Testing Small Sandbox Development Small Development Production environment and go-live assessment When we are preparing to go live, the first thing we need is access to our production environment. Project-wise, a production environment is deployed after all customisations are code-complete, UAT is finished, the customer has signed off, and there are no blocking issues. In a go-live assessment, a solution architect is assigned to review the project and provide an assessment of potential risks, best practices, and recommendations for a successful go-live. In some cases, the solution architect might highlight risk factors and ask for a mitigation plan. When the assessment is completed, the solution architect will indicate that you’re ready to request the production environment.\nGeneral recommendations Plan for environments early in the project as this may impact the project’s budget and consider the lead time needed to purchase the environment as this may impact the project timeline. Revisit the plan at regular intervals. Define a consistent naming standard for your environments. Have a regular schedule to deploy updates and import fresh data Please note that the production environment is used exclusively for running your business operations and shouldn’t be used for testing. More, the production environment is not available until the go-live assessment is finalized, a stage in which most of the testing should already be complete. You will be able to perform the cutover and, if planned, “mock” the cutover in production. Keep all environments in the same region if your business is in one region. For example, avoid having a test environment in one geographical location and production in another. Deploy environments by using an unnamed account. Assign the environments to an owner who will be responsible for their status and maintenance. It is strongly recommended using the same dedicated admin account in all environments. Test environments landscape example Test environment Purpose Release version (actual on Jan 10) Prod Use by end users Release 1.1 Pre-Prod Checking any release candidates before deployment to Prod Release 1.1 Training Training-related activities, MAT phase, DDM MAT phase Release 1.1 MAT UAT and regression for BAU releases, DDM UAT phase Release 1.1 UAT UAT phase for the ongoing release including functional, integration, data migration, and system regression testing. Penetration testing Release 1.2 E2E UAT phase for the ongoing or future releases including functional, integration, data migration, and system regression testing Release 1.2 Sys Test Sys Test phase, automation testing. Performance testing considering env limitation (size, scale, etc.) Release 1.3 Dev Unit Testings Release 1.3 ","date":"5 July 2022","externalUrl":null,"permalink":"/environment-strategy/","section":"Articles","summary":"Overview Businesses should believe that every team is in the business of creating great customer experiences.\nTo achieve that, the application must do more than just provide control, reporting and audibility. The business needs to tap into data signals from across its business and use them to drive ongoing improvements in the products, services, and experiences they intend to deliver to its customers.\n","title":"Environment Strategy","type":"articles"},{"content":"With Microsoft now owning GitHub, the technical teams have been integrated, resulting in Azure DevOps and GitHub having the same leadership and personnel. The long-term strategic direction will be GitHub, but there is no plan for Azure DevOps to go into maintenance/sunset; therefore, choosing Azure DevOps is entirely OK in short to (undefined) medium term. Azure DevOps is currently in the early stages of development. When migration tools are needed, Microsoft will give them.\nSome holes in GitHub have now been remedied, most notably in native CI/CD support (Actions, forked from Azure DevOps pipelines). As a result, I’d say they’re roughly equal currently. Because GitHub is the strategic approach, I’d recommend looking at GitHub and leveraging capabilities like Advanced Security that Azure DevOps lacks. Instead, I would choose Azure DevOps for the following reasons:\nCloud Service with Data Sovereignty in the UK GitHub Enterprise Cloud is currently only available in the United States, whereas Azure DevOps Services can be hosted in the Azure UK South zone. This isn’t an issue if you’re utilising the self-hosted versions (GitHub Enterprise Server and Azure DevOps Server), as you may put them wherever you like (on-prem or cloud).\nWork tracking GitHub Issues does not have the same task tracking and planning capabilities as Azure Boards. This is changing, and GitHub’s new Projects boards go a long way toward filling the void, but it’s still not up to par.\nCustomers are increasingly opting for Azure DevOps (for Boards) and GitHub in this area (for everything else). This is reflected in licensing, which effectively combines the two.\nTFVC Because GitHub only supports git (and SVN clients), Azure DevOps is the best solution for long-time TFS customers who use TFVS for version management.\nThe choice is yours to which pipeline you go down\n","date":"3 May 2022","externalUrl":null,"permalink":"/end-of-the-road-for-azure-devops/","section":"Articles","summary":"With Microsoft now owning GitHub, the technical teams have been integrated, resulting in Azure DevOps and GitHub having the same leadership and personnel. The long-term strategic direction will be GitHub, but there is no plan for Azure DevOps to go into maintenance/sunset; therefore, choosing Azure DevOps is entirely OK in short to (undefined) medium term. Azure DevOps is currently in the early stages of development. When migration tools are needed, Microsoft will give them.\n","title":"End of the Road For Azure DevOps?","type":"articles"},{"content":"","date":"24 January 2022","externalUrl":null,"permalink":"/categories/agile/","section":"Categories","summary":"","title":"Agile","type":"categories"},{"content":"“The minimum viable product is that product which has just those features (and no more) that allows you to ship a product that resonates with early adoptors; some of whom will pay you money or give you feedback” – Eric Ries\n","date":"24 January 2022","externalUrl":null,"permalink":"/mvp-minimum-viable-product/","section":"Articles","summary":"“The minimum viable product is that product which has just those features (and no more) that allows you to ship a product that resonates with early adoptors; some of whom will pay you money or give you feedback” – Eric Ries\n","title":"MVP – Minimum Viable Product","type":"articles"},{"content":"There are a variety of techniques to deploy new updates for environments to production, so choosing the right strategy is an important decision, weighing the options in terms of the impact of change on the system and the end-users.\nThe following strategies need to be considered:\nRecreate: Version A is terminated then version B is rolled out. Ramped (also known as rolling-update or incremental): Version B is slowly rolled out and replacing version A. Blue/Green: Version B is released alongside version A, then the traffic is switched to version B. Canary: Version B is released to a subset of users, then proceed to a full rollout. A/B testing: Version B is released to a subset of users under specific condition. Shadow: Version B receives real-world traffic alongside version A and doesn’t impact the response. Let me take you through each strategy and see which would best fit a particular use case.\nRecreateThe recreate strategy is a dummy deployment which consists of shutting down version A then deploying version B after version A is turned off. This technique implies downtime of the service that depends on both shutdown and boot duration of the application.\nPros:\nEasy to setup. Application state entirely renewed. Cons:\nHigh impact on the user, expect downtime that depends on both shutdown and boot duration of the application. RampedThe ramped deployment strategy consists of slowly rolling out a version of an application by replacing instances one after the other until all the instances are rolled out. It usually follows the following process: with a pool of version A behind a load balancer, one instance of version B is deployed. When the service is ready to accept traffic, the instance is added to the pool. Then, one instance of version A is removed from the pool and shut down.\nDepending on the system taking care of the ramped deployment, you can tweak the following parameters to increase the deployment time:\nParallelism, max batch size: Number of concurrent instances to roll out. Max surge: How many instances to add in addition of the current amount. Max unavailable: Number of unavailable instances during the rolling update procedure. Pros:\nEasy to set up. Version is slowly released across instances. Convenient for stateful applications that can handle rebalancing of the data. Cons:\nRollout/rollback can take time. Supporting multiple APIs is hard. No control over traffic. Blue/Green\nThe blue/green deployment strategy differs from a ramped deployment; version B (green) is deployed alongside version A (blue) with precisely the same amount of instances. After testing that the new version meets all the requirements, traffic is switched from version A to version B at the load balancer level.\nPros:\nInstant rollout/rollback. Avoid versioning issue, the entire application state is changed in one go. Cons:\nExpensive as it requires double the resources. Proper test of the entire platform should be done before releasing to production. Handling stateful applications can be hard. CanaryA canary deployment gradually shifts production traffic from version A to version B. Usually, the traffic is split based on weight. For example, 90 per cent of the requests go to version A, 10 per cent go to version B.\nThis technique is mostly used when the tests are lacking or not reliable or if there is little confidence about the stability of the new release on the platform.\nPros:\nVersion released for a subset of users. Convenient for error rate and performance monitoring. Fast rollback. Con:\nSlow rollout. A/B testing\nA/B testing deployments are routing a subset of users to a new functionality under specific conditions. It is usually a technique for making business decisions based on statistics rather than a deployment strategy. However, it is related and can be implemented by adding extra functionality to a canary deployment, briefly discussing it here.\nThis technique is widely used to test the conversion of a given feature and only roll out the version that converts the most.\nHere is a list of conditions that can be used to distribute traffic amongst the versions:\nBy browser cookie Query parameters Geolocalisation Technology support: browser version, screen size, operating system, etc. Language Pros:\nSeveral versions run in parallel. Full control over the traffic distribution. Cons:\nRequires intelligent load balancer. Hard to troubleshoot errors for a given session, distributed tracing becomes mandatory. ShadowA shadow deployment consists of releasing version B alongside version A, fork version A’s incoming requests and sending them to version B without impacting production traffic. This is particularly useful to test production load on a new feature. A rollout of the application is triggered when stability and performance meet the requirements.\nThis technique is relatively complex and needs special requirements, especially with egress traffic. For example, given a shopping cart platform, if you want to shadow test the payment service, you can end up having customers paying twice for their order. In this case, you can solve it by creating a mocking service that replicates the response from the provider.\nPros:\nPerformance testing of the application with production traffic. No impact on the user. No rollout until the stability and performance of the application meet the requirements. Cons:\nExpensive as it requires double the resources. Not a true user test and can be misleading. Complex to setup. Requires mocking service for certain cases. Summary\nThere are multiple ways to deploy a new version of an application, and it depends on the needs and budget. When releasing to development/staging environments, a recreate or ramped deployment is usually a good choice. When it comes to production, a ramped or blue/green deployment is usually a good fit, but proper testing of the new platform is necessary.\nBlue/green and shadow strategies have more impact on the budget as it requires double resource capacity. If the application lacks in tests or has little confidence about the impact/stability of the software, then a canary, a/ b testing or shadow release can be used. Suppose your business requires testing a new feature amongst a specific pool of users that can be filtered depending on some parameters like geolocation, language, operating system or browser features. In that case, you may want to use the a/b testing technique.\nLast but not least, a shadow release is complex and requires extra work to mock egress traffic which is mandatory when calling external dependencies with mutable actions (email, bank, etc.). However, this technique can be helpful when migrating to new database technology and using shadow traffic to monitor system performance under load.\nDeployment Strategies\nWhen it comes to production, a ramped or blue/green deployment is usually a good fit, but proper testing of the newthe platform is necessary.\nBlue/green and shadow strategies have more impact on the budget as it requires double resource capacity. If the application lacks in tests or has little confidence about the impact/stability of the software, then a canary, a/b testing or shadow release can be used.\nSuppose you require testing a new feature amongst a specific pool of users that can be filtered depending on some parameters like geolocation, language, operating system or browser features. In that case, you may want to use the a/b testing technique.\nOriginal article\n","date":"18 January 2022","externalUrl":null,"permalink":"/deployment-strategies/","section":"Articles","summary":"There are a variety of techniques to deploy new updates for environments to production, so choosing the right strategy is an important decision, weighing the options in terms of the impact of change on the system and the end-users.\nThe following strategies need to be considered:\n","title":"Deployment Strategies","type":"articles"},{"content":"As part of our customer engagement, we have defined a naming convention for GitHub repositories. We have ideas around what conventions made sense, although the type of work influences these. As we tend to spend some of your engineering time working with different languages, conventions around naming formats make sense to the engineers. These, of course, might not make sense to individuals in other fields. GitHub, by default, prevents certain characters from being included in the repository name, but how do we use those left to provide meaning to engineers, testing engineers, and others who use the code base and GitHub day in and day out? Semantics Semantics is the study of meaning when applied to linguistics, semiotics programming languages, and logic. You might be familiar with the application of semantics in a programming language, as distinct from syntax. Furthermore, software developers and DevSecOps engineers will likely have come across semantic versioning (semver.org), aiming to provide meaning to application version numbers. We can use a semantic approach to repository naming. Tackling the problem GitHub maintains a style guide standard (https://github.com/agis/git-style-guide) but does not explicitly list a standard for the repository name itself. Investigating other articles, guides, repositories, and stack overflow suggested the consensus was to use hyphens to separate portions of the repository name. Some organisations have taken the step to formalise this. One example is the British Columbia Policy Framework for GitHub Document Naming Repos This document enumerates criteria for a repository name, which includes: Descriptive Readable Consistent Contextual Future-friendly Extensible Reusable Brief (short/succinct) All of these seem like very reasonable suggestions. Using this as a guideline, we have broken down our initial draft standard into three sections separated by hyphens: section1-section2-section3 This format consists of sections defining the project name, purpose, and framework or language. An example of what this might look like would be: project1-restapi-python Each of these sections could be further hyphenated if two words needed to be split, for example, “rest-api”. Conventions Having drawn up a semantic-based naming structure that drew on general research, the structure we are proposing is: section1-section2 Including the framework or programming language is not that useful, as many repositories mixed languages—for example, PHP and JavaScript. Therefore, the format product/project name and the repository purpose, would be more suitable. For example: project1-rest-api There is no one solution that will fit all; therefore, we have come up with two, which addresses both business and project needs and general needs of common repositories. This approach is suited to a project team or department where multiple products exist and comprise of sub-components, such as microservices. [product/project name]-[purpose] e.g. myproject-rest-api Structure hierarchy: Top folder Sub folder1 Sub folder 1-1 Sub folder 1-2 Sub folder 2 Sub folder 2-1 Sub folder 2-2 Where a more common pattern would reflect an Open-Source and common library approach: [language/framework]-[product/project] e.g. python-security-scripts There may be more than one correct approach, but teams must use a convention that works for them and stick to it. Overall, this helps maintain repository hygiene and helps engineers deal with dozens of repositories to quickly find what they are looking for. ","date":"4 November 2021","externalUrl":null,"permalink":"/github-naming-repositories/","section":"Articles","summary":"As part of our customer engagement, we have defined a naming convention for GitHub repositories. We have ideas around what conventions made sense, although the type of work influences these. As we tend to spend some of your engineering time working with different languages, conventions around naming formats make sense to the engineers. These, of course, might not make sense to individuals in other fields. ","title":"GitHub Naming Repositories","type":"articles"},{"content":"GISTS – engage in chat or gossip. “I need a good friend I can always gist with.” It is always good to chat with others, which is how we learn from each other. So why don’t project teams chat with each other? In this day and age of working from home, it is becoming more and more critical to form a social network, which helps not only with mental health but also work-related ideas and time. Engineers are renowned for working in silos and disappearing for days at a time; they are full of valuable insights and knowledge, but how do we get them to talk and share their knowledge? Along comes Gists which lets engineers share code snippets, entire files, or even applications. You can also use gists to save and share console output when running, debugging, or testing your code. Gist is an easy method to share snippets or excerpts of data with others. A gist can be a string of code, a bash script or some other small piece of data. GitHub hosts these bits of information as a repository. Using gist has all the benefits of utilizing a GitHub repository and also provides a more lightweight way of utilizing GitHub’s versioning features. Each gist is a repository that can be cloned or forked by other people. https://docs.github.com/en/github/writing-on-github/editing-and-sharing-content-with-gists/creating-gists\nA gist can be either public or secret. When you are logged in to GitHub, it will show up in your dashboard when you create a gist. You can also drag and drop a file onto your gist editor, and it will be added Not only are gists free to create and store on GitHub, but they are also easy to create. You can add a new gist, modify, and delete files and code entirely from your browser. Lastly, there is no need to download or install a program to use gist. It is recommended that the engineers create general-purpose shared gists for use within the engineering teams. ","date":"4 November 2021","externalUrl":null,"permalink":"/gists/","section":"Articles","summary":"GISTS – engage in chat or gossip. “I need a good friend I can always gist with.” It is always good to chat with others, which is how we learn from each other. So why don’t project teams chat with each other? In this day and age of working from home, it is becoming more and more critical to form a social network, which helps not only with mental health but also work-related ideas and time. ","title":"gists","type":"articles"},{"content":"","date":"9 October 2021","externalUrl":null,"permalink":"/categories/red-hat/","section":"Categories","summary":"","title":"Red Hat","type":"categories"},{"content":"The installation model for OCP 4.x is different than 3.x and there are no Azure Resource Manager templates available for deploying OCP 4.x in Azure https://docs.microsoft.com/en-us/azure/virtual-machines/linux/openshift-container-platform-4x\nhttps://docs.openshift.com/aro/4/welcome/index.html\nAzure Red Hat OpenShift 4 Documentation Important Azure Red Hat OpenShift is supported by Red Hat and Microsoft. As of February 2021, the documentation will be hosted by Microsoft and Red Hat as outlined below. Microsoft Azure documentation Red Hat OpenShift documentation Overview of Azure Red Hat OpenShift Creating a cluster Getting support How-to guides and tutorials Azure CLI reference Overview of OpenShift architecture Release Notes Developing on OpenShift Managing your cluster https://docs.microsoft.com/en-us/azure/openshift/\n","date":"9 October 2021","externalUrl":null,"permalink":"/requirements-for-azure-red-hat-openshift/","section":"Articles","summary":"The installation model for OCP 4.x is different than 3.x and there are no Azure Resource Manager templates available for deploying OCP 4.x in Azure https://docs.microsoft.com/en-us/azure/virtual-machines/linux/openshift-container-platform-4x\nhttps://docs.openshift.com/aro/4/welcome/index.html\nAzure Red Hat OpenShift 4 Documentation Important Azure Red Hat OpenShift is supported by Red Hat and Microsoft. As of February 2021, the documentation will be hosted by Microsoft and Red Hat as outlined below. ","title":"Requirements for Azure Red Hat OpenShift","type":"articles"},{"content":"What is Red Hat OpenShift?\nOpenShift is Kubernetes, but it is also more than Kubernetes it is a collection of other software services that gives you the ability to run an entire Kubernetes environment, which includes:\nKubernetes Grafana Tekton Prometheus Cri-o Red Hat Enterprise Linux CoreOS They all work together as a single distributed set of software to easily run Kubernetes in production.\nKubernetes\nProduction-Grade Container Orchestration\nGrafana Dashboard anything. Observe everything.\nQuery, visualize, alert on, and understand your data no matter where it’s stored. With Grafana you can create, explore and share all of your data through beautiful, flexible dashboards.\nTekton\nTekton is a powerful and flexible open-source framework for creating CI/CD systems, allowing developers to build, test, and deploy across cloud providers and on-premise systems.\nPrometheus\nFrom metrics to insight. Power your metrics and alerting with a leading open-source monitoring solution.\nCri-o\nLightweight container runtime for Kubernetes\nRed Hat Enterprise Linux CoreOS\nRed Hat Enterprise Linux CoreOS (RHCOS) represents the next generation of single-purpose container operating system technology. Created by the same development teams that created Red Hat Enterprise Linux Atomic Host and CoreOS Container Linux, RHCOS combines the quality standards of Red Hat Enterprise Linux (RHEL) with the automated, remote upgrade features from Container Linux.\n","date":"8 September 2021","externalUrl":null,"permalink":"/red-hat-openshift/","section":"Articles","summary":"What is Red Hat OpenShift?\nOpenShift is Kubernetes, but it is also more than Kubernetes it is a collection of other software services that gives you the ability to run an entire Kubernetes environment, which includes:\n","title":"Red Hat OpenShift","type":"articles"},{"content":"","date":"13 July 2021","externalUrl":null,"permalink":"/categories/.net-4.0/","section":"Categories","summary":"","title":".NET 4.0","type":"categories"},{"content":"On big enterprise projects, memory leaks are like rodents in a factory. You might not notice when there are a few of them, but you always have to be on guard in case they overpopulate, infesting the factory will cause the closer and failure of the factory.\nDetect a Memory Leak problem with the Diagnostic Tool Window If you go to Debug | Windows | Show Diagnostic Tools, you’ll see this window. If you’re like me, you probably saw this tool window after installing Visual Studio, closed it immediately, and never thought of it again. The Diagnostic Tools Window can be quite useful though. It can easily help you detect 2 problems: Memory Leaks and GC Pressure.\nWhen you have Memory Leaks, the Process Memory graph looks like this:\nYou can see with the yellow lines coming from the top that the GC is trying to free memory, but it still keeps rising.\nWhen you have GC Pressure, the Process Memory graph looks like this:\nGC Pressure is when you are creating new objects and disposing of them too quickly for the garbage collector to keep up. As you see in the picture, the memory is close to its limit and the GC bursts are very frequent.\nYou won’t be able to find specific memory leaks this way, but you can detect that you have a memory leak problem, which is useful by itself. In Enterprise Visual Studio, the Diagnostics Window also includes a built-in memory profiler, which does allow to find the specific leak. Detect Memory Leak problems with the Task Manager, Process Explorer or PerfMon PerfMon is a bit harder to use but can show a nice graph of your memory usage over time. Here’s a graph of my application that endlessly allocates memory without freeing it. I’m using the Process | Private Bytes counter.\nNote that this method is notoriously unreliable. You might have an increase in memory usage just because the GC didn’t collect it yet. There’s also the matter of shared memory and private memory, so you can both miss memory leaks and/or diagnose memory leaks that aren’t your own (explanation). Finally, you might mistake memory leaks for GC Pressure. In this case, you don’t have a memory leak but you create and dispose of objects so fast that the GC doesn’t keep up.\nDespite the disadvantages, I mention this technique because it’s both easy to use and sometimes your only tool. It’s also a decent indicator something is wrong when observing for a very long period of time.\nUse a memory profiler to detect memory leaks A memory profiler is like the Chef’s Knife of handling memory leaks. It’s the main tool to find and fix them. While other techniques can be easier to use or cheaper (profiler licenses are costly), it’s best to be proficient by with at least one memory profiler to effectively solve memory leak problems.\nThe big names in .NET memory profilers are: dotMemory, SciTech Memory Profiler and ANTS Memory Profiler. There’s also a “free” profiler if you have Visual Studio Enterprise.\nAll memory profilers work in a similar way. You can either attach to a running process or open a Dump file. The profiler will create a Snapshot of your process’ current memory heap. You can analyze the snapshot in all kinds of ways For example, here’s a list of all the allocated objects in the current snapshot:\nYou can see how many instances of each type are allocated, how much memory they take, and the reference path to a GC Root.\nA GC Root is an object which the GC can’t free, so anything that the GC root references also can’t be freed. Static objects and the local objects in the current active Threads are GC Roots. Read more in Understanding Garbage Collection in .NET. The quickest and most useful profiling technique is to compare 2 snapshots where the memory should return to the same state. The first snapshot is taken before an operation, and another snapshot is taken after the operation. The exact steps are:\nStart with some kind of Idle state in your application. This could be the Main Menu or something similar. Take a snapshot with the Memory profiler by attaching-to-process or saving a Dump. Run an operation where you suspect a memory leak is created. Return to the Idle state at the end of it. Take a second snapshot. Compare both snapshots with your memory profiler. Investigate the New-Created-Instances, they are probably memory leaks. Examine the “path to GC Root” and try to understand why those objects weren’t freed. Here’s a great video where 2 snapshots are compared in SciTech memory profiler and the memory leak is found:\nBeware of common memory leak sources There’s always a risk of causing a memory leak, but there are certain patterns that are much more likely to do so. I suggest to be extra careful when using these, and proactively check for memory leaks with techniques like the last best practice.\nHere are some of the more common offenders:\nEvents in .NET are notorious for causing memory leaks. You can innocently subscribe to an event, causing a damaging memory leak without even suspecting. This subject is so important that I dedicated an entire article to it: 5 Techniques to avoid Memory Leaks by Events in C# .NET you should know Static variables, collections, and static events in-particular should always look suspicious. Remember that all static variables are GC Roots, so they are never collected by the GC. Caching functionality – Any type of caching mechanism can easily cause memory leaks. By storing cache information in-memory, eventually, it will fill up and cause an OutOfMemory exception. The solution can be to periodically delete older caching or limit your caching amount. WPF Bindings can be dangerous. The rule of thumb is to always bind to a DependencyObject or to a INotifyPropertyChangedobject. When you fail to do so, WPF will create a strong reference to your binding source (meaning the ViewModel) from a static variable, causing a memory leak. More information on WPF Binding leaks in this helpful StackOverflow thread Captured members – It might be clear that an Event Handler Method means an object is referenced, but when a variable is Captured in an anonymous method, then it’s also referenced. Here’s an example of a memory leak: public class MyClass { private int _wiFiChangesCounter = 0; public MyClass(WiFiManager wiFiManager) { wiFiManager.WiFiSignalChanged += (s, e) =\u0026amp;gt; _wiFiChangesCounter++; }\u0026lt;/code\u0026gt;\u0026lt;/pre\u0026gt; Threads that never terminate – The Live Stack of each of your threads is considered a GC Root. This means that until a thread terminates, any references from its variables on the Stack will not be collected by the GC. This includes Timers as well. If your Timer’s Tick Handler is a method, then the method’s object is considered referenced and will not be collected. Here’s an example of a memory leak: public class MyClass { public MyClass(WiFiManager wiFiManager) { Timer timer = new Timer(HandleTick); timer.Change(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5)); } private void HandleTick(object state) { // do something }\u0026lt;/code\u0026gt;\u0026lt;/pre\u0026gt; Use the Dispose pattern to prevent unmanaged memory leaks Your .NET application constantly uses unmanaged resources. The .NET framework itself relies heavily on unmanaged code for internal operations, optimization, and Win32 API. Anytime you use Streams, Graphics, or Files for example, you are probably executing unmanaged code.\n.NET framework classes that use unmanaged code usually implement IDisposable. That’s because unmanaged resources need to be explicitly freed, and that happens in the Dispose method. Your only job is to remember and call the Dispose method. If possible, use the using statement for that.\npublic void Foo() { using (var stream = new FileStream(@\"C:\\Temp\\SomeFile.txt\", FileMode.OpenOrCreate)) { // do stuff }// stream.Dispose() will be called even if an exception occurs\u0026lt;/code\u0026gt;\u0026lt;/pre\u0026gt; he using statement transforms the code into a try / finally statement behind the scenes, where the Dispose method is called in the finally clause.\nBut, even if you don’t call the Dispose method, those resources will be freed because .NET classes use the Dispose Pattern. This basically means that if Dispose wasn’t called before, it’s called from the Finalizer when the object is garbage collected. That is, if you don’t have a memory leak and the Finalizer really is called.\nWhen you’re allocating unmanaged resources yourself, then you definitely should use the Dispose pattern. Here’s an example:\npublic class MyClass : IDisposable { private IntPtr _bufferPtr; public int BUFFER_SIZE = 1024 * 1024; // 1 MB private bool _disposed = false; public MyClass() { _bufferPtr = Marshal.AllocHGlobal(BUFFER_SIZE); } protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { // Free any other managed objects here. } // Free any unmanaged objects here. Marshal.FreeHGlobal(_bufferPtr); _disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~MyClass() { Dispose(false); } }\nThe point of this pattern is to allow explicit disposal of resources. But also to add a safeguard that your resources will be disposed during garbage collection (in the Finalizer) if the Dispose() wasn’t called.\nThe GC.SuppressFinalize(this) is also important. It makes sure the Finalizer isn’t called on garbage collection if the object was already disposed of. Objects with Finalizers are freed differently and much more costly. The Finalizer is added to something called the F-Reachable-Queue, which makes the object survive an additional GC generation. There are also other complications.\nAdd Memory Telemetry from Code Sometimes, you might want to periodically log your memory usage. Maybe you suspect your production Server has a memory leak. Perhaps you want to take some action when your memory reaches a certain limit. Or maybe you’re just in the good habit of monitoring your memory.\nThere’s a lot of information we can get from the app itself. Getting current memory in use is as simple as:\nProcess currentProc = Process.GetCurrentProcess(); var bytesInUse = currentProc.PrivateMemorySize64; For more information, you can use the PerformanceCounter class that’s used for PerfMon:\nPerformanceCounter ctr1 = new PerformanceCounter(\"Process\", \"Private Bytes\", Process.GetCurrentProcess().ProcessName); PerformanceCounter ctr2 = new PerformanceCounter(\".NET CLR Memory\", \"# Gen 0 Collections\", Process.GetCurrentProcess().ProcessName); PerformanceCounter ctr3 = new PerformanceCounter(\".NET CLR Memory\", \"# Gen 1 Collections\", Process.GetCurrentProcess().ProcessName); PerformanceCounter ctr4 = new PerformanceCounter(\".NET CLR Memory\", \"# Gen 2 Collections\", Process.GetCurrentProcess().ProcessName); PerformanceCounter ctr5 = new PerformanceCounter(\".NET CLR Memory\", \"Gen 0 heap size\", Process.GetCurrentProcess().ProcessName); //... Debug.WriteLine(\"ctr1 = \" + ctr1 .NextValue()); Debug.WriteLine(\"ctr2 = \" + ctr2 .NextValue()); Debug.WriteLine(\"ctr3 = \" + ctr3 .NextValue()); Debug.WriteLine(\"ctr4 = \" + ctr4 .NextValue()); Debug.WriteLine(\"ctr5 = \" + ctr5 .NextValue()); Information from any perfMon counter is available, which is plenty.\nYou can go even deeper though. CLR MD (Microsoft.Diagnostics.Runtime) allows you to inspect your current memory heap and get any possible information. For example, you can print all the allocated types in memory, including instance counts, paths to roots and so on. You pretty much got a memory profiler from code.\nTo get a whiff of what you can achieve with CLR MD, check out Dudi Keleti’s DumpMiner.\nAll this information can be logged to a file, or even better, to a telemetry tool like Application Insights.\nTest for memory leaks It’s a great practice to proactively test for memory leaks. And it’s not that hard. Here’s a short pattern you can use:\n[Test] void MemoryLeakTest() { var weakRef = new WeakReference(leakyObject) // Ryn an operation with leakyObject GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.IsFalse(weakRef.IsAlive); } Original article: Find, Fix, and Avoid Memory Leaks in C# .NET: 8 Best Practices\n","date":"13 July 2021","externalUrl":null,"permalink":"/memory-leaks-in-net/","section":"Articles","summary":"On big enterprise projects, memory leaks are like rodents in a factory. You might not notice when there are a few of them, but you always have to be on guard in case they overpopulate, infesting the factory will cause the closer and failure of the factory.\n","title":"Memory Leaks in .NET","type":"articles"},{"content":"","date":"5 May 2021","externalUrl":null,"permalink":"/categories/net-core/","section":"Categories","summary":"","title":"\u003eNET Core","type":"categories"},{"content":"If you need a background task within .Net Core to be run at set times we can use the Hosted Service provided from the service within .Net Core.\nA timed background task makes use of the System.Threading.Timer class. The timer triggers the task’s DoWork method. The timer is disabled on StopAsync and disposed when the service container is disposed on Dispose:\npublic class TimedHostedService : IHostedService, IDisposable { private int executionCount = 0; private readonly ILogger\u0026amp;lt;TimedHostedService\u0026amp;gt; _logger; private Timer _timer; public TimedHostedService(ILogger\u0026amp;amp;lt;TimedHostedService\u0026amp;amp;gt; logger) { _logger = logger; } public Task StartAsync(CancellationToken stoppingToken) { _logger.LogInformation(\u0026quot;Timed Hosted Service running.\u0026quot;); _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5)); return Task.CompletedTask; } private void DoWork(object state) { var count = Interlocked.Increment(ref executionCount); _logger.LogInformation( \u0026quot;Timed Hosted Service is working. Count: {Count}\u0026quot;, count); } public Task StopAsync(CancellationToken stoppingToken) { _logger.LogInformation(\u0026quot;Timed Hosted Service is stopping.\u0026quot;); _timer?.Change(Timeout.Infinite, 0); return Task.CompletedTask; } public void Dispose() { _timer?.Dispose(); } }\nThe Timer doesn’t wait for previous executions of DoWork to finish, so the approach shown might not be suitable for every scenario. Interlocked.Increment is used to increment the execution counter as an atomic operation, which ensures that multiple threads don’t update executionCount concurrently.\nThe service is registered in IHostBuilder.ConfigureServices (Program.cs) with the AddHostedService extension method:\nservices.AddHostedService\u0026lt;TimedHostedService\u0026gt;(); Original article\n","date":"5 May 2021","externalUrl":null,"permalink":"/hosted-background-timer-task/","section":"Articles","summary":"If you need a background task within .Net Core to be run at set times we can use the Hosted Service provided from the service within .Net Core.\nA timed background task makes use of the System.Threading.Timer class. The timer triggers the task’s DoWork method. The timer is disabled on StopAsync and disposed when the service container is disposed on Dispose:\n","title":"Hosted Background timer task","type":"articles"},{"content":"A little hidden gem within .Net Core is the ability to run a Hosted Service inside the application. This allows for your service to run in a different thread to the main application, but keeps everything together though the need to host a separate service.\nIt’s worth taking a look over the Microsoft documentation on how to go about this:\nhttps://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1\u0026amp;tabs=visual-studio\nSetting up is easy as adding a single line to your StartUp method\nservices.AddHostedService\u0026lt;YourMessageHandler\u0026gt;(); ","date":"5 May 2021","externalUrl":null,"permalink":"/hosting-a-service-inside-asp-net-core/","section":"Articles","summary":"A little hidden gem within .Net Core is the ability to run a Hosted Service inside the application. This allows for your service to run in a different thread to the main application, but keeps everything together though the need to host a separate service.\n","title":"Hosting a service inside  ASP.NET Core","type":"articles"},{"content":"If you are like me you will have been using ILogger in DotNet Core for some time, but you’ll have noticed there are many ways to use the logger, I found this useful article by Rico Suter going over some recommendation and best practices.\nhttps://blog.rsuter.com/logging-with-ilogger-recommendations-and-best-practices/\nThis article presents recommendations and best practices for using the ILogger-based logging system included with.NET Core.\nIntroduction The Microsoft.Extensions include logging interfaces. Abstractions.Logging The NuGet package contains implementations for different logging backends and sinks, as well as basic logging abstractions.\nA logging backend is a storage location for logs, such as archives, Application Insights (AI), Seq, Kibana, and so on. Sinks are the name for them in the Serilog logging library.\nILogger vs ILoggerProvider vs ILoggerFactory ILogger\nThe ILogger interface’s job is to build logging scopes and write a log message of a specified log level. The interface only exposes a few generic log methods, which are then used by “external” extension methods such as LogInformation and LogError.\nILoggerProvider\nA logger provider is a software implementation of a logging sink, such as a terminal, Application Insights, archives, or Serilog (an adapter to the Serilog logging abstraction). The only duty of the ILoggerProvider is to build ILogger instances that log to an actual sink. A logger instance provided by a logger provider can only log to the logger provider with which it is associated.\nILoggerFactory\nThe ILoggerFactory logger factory instance is the logging system’s bootstrapper: It’s used to link logger providers and build logger instances, which can be typed (ILoggerT\u0026gt;) or untyped (ILoggerUntyped) (ILogger). All registered logger providers will receive logs from these logger instances.\nLog statements Use structured logs It is recommended to always use semantic/structured logs so that the logging backend receives the string with placeholders and its values separately. It is then able to just replace them in its UI on demand. This way each log statement preserves all associated properties and a template hash (in AI “MessageTemplate”) which allows the backend to apply advanced filtering or search for all logs of a given type.\nlogger.LogWarning(\"The person {PersonId} could not be found.\", personId); The previous statement will log the following properties to Application Insights:\nMessage: The person 5 could not be found. MessageTemplate: The person {PersonId} could not be found. PersonId: 5 Advantages of structured logs:\nProperties are stored as seperate custom properties of the log entry and you can filter based on them in the logging backend A message template/message hash is stored so that you can easily query for all logs of a given log statement type Serialization of properties only happens if the log is actually written (not the case with string interpolation) Disadvantages:\nThe order of the parameters in the C# log statement have to be correct and this cannot be statically checked by the compiler in the same way as it’s done in interpolated strings Always pass exception as first parameter To log an exception, always pass the exception object as first argument:\nlogger.LogWarning(exception, \"An exception occured\") Otherwise, it is treated as custom property and if it has no placeholder in the message it will not end up in the log. Also, the formatting and storage are exceptions specific if you use the correct method overload.\nAlways use placeholders and avoid string interpolation To ensure that a message template is correctly logged and properties are transferred as custom properties, you always need to log properties with placeholders in the correct order, e.g.\nlogger.LogWarning(\"The person {PersonId} could not be found.\", personId); Never use string interpolation because the replacement will be done in your application and the logging backend has no longer access to the message template and individual custom properties:\nlogger.LogWarning($\"The person {personId} could not be found.\"); Another downside of string interpolation is that objects are always serialized into text in your app even if the log is not actually written because there is a log level filter configured.\nDo not use dots in property names Avoid using dots in placeholder property names (e.g Device.ID) because some ILogger implementations (e.g. Serilog) do not support this. The main reason for this is that some logging backends cannot handle these property names and thus Serilog has to implement the lowest common denominator.\nScopes Use scopes to add custom properties to multiple log entries Use scopes to transparently add custom properties to all logs in a given execution context.\nusing (logger.BeginScope( new Dictionary\u0026amp;lt;string, object\u0026gt; { {\"PersonId\", 5 } })) { logger.LogInformation(\"Hello\"); logger.LogInformation(\"World\"); } Now both log statements will be logged with an additional PersonId property. Most scope implementations even work correctly in parallel code because they use async contexts.\nYou should create scopes for logical contexts, regions or per unit of work; for example:\nPer HTTP request Per event queue message Per database transaction In each of these scopes you should set the following properties if available:\nCorrelation ID (use the X-Request-ID HTTP header to read it in HTTP request scopes) Don’t forget to pass the correlation ID when calling other HTTP endpoints In Application Insights the property should be called operation_id Transaction ID Consider adding a scope identifier to filter logs by scope In order to be able to show all logs of a given custom scope, I implemented a simple extension method which automatically adds a scope identifier and uses value tuples to specify properties for all log entries in the scope:\npublic static IDisposable BeginNamedScope(this ILogger logger, string name, params ValueTuple\u0026amp;lt;string, object\u0026gt;[] properties) { var dictionary = properties.ToDictionary(p =\u0026gt; p.Item1, p =\u0026gt; p.Item2); dictionary[name + \".Scope\"] = Guid.NewGuid(); return logger.BeginScope(dictionary); } This exention method can be used like this:\nforeach (var message in messages) { using (logger.BeginNamedScope(\"Message\", (\"Message.Id\", message.Id), (\"Message.Length\", message.Length))) { logger.LogInformation(\"Hello\"); logger.LogInformation(\"World\"); } } Both log entries will now have a Message.Scope property with the same value: Using this property you are now able to show all logs of a given scope in your logging backend.\nUse scopes to add additional custom properties to a single entry If you want to add additional properties to a log statement which should not be part of the message template, use a “short lived” scope:\nusing (logger.BeginPropertyScope((\"UserId\", \"CurrentUserId\"))) { logger.LogTrace(\"The message has been processed.\"); } The used extension method to use value tuples looks like this:\npublic static IDisposable BeginPropertyScope(this ILogger logger, params ValueTuple\u0026amp;lt;string, object\u0026gt;[] properties) { var dictionary = properties.ToDictionary(p =\u0026gt; p.Item1, p =\u0026gt; p.Item2); return logger.BeginScope(dictionary); } Organization Use a list of conceptual property names You should build up a list of constant log entry property names (usually set with scopes) for your domain so that always the same name is used for them. For example always use UserId instead of Message.UserId and Request.UserId so that it’s easier to filter by user id over all log entries.\nLog levels It is recommended to think about what available log level to use. With this differentiation you can automatically create alerts, reports and issues.\nFor more information about when to use which log level, head over to the official documentation.\nUse correct log levels Here is a summary of the available .NET log levels and their meaning:\nTrace/Verbose: Logs that contain the most detailed messages. These messages may contain sensitive application data. These messages are disabled by default and should never be enabled in a production environment. Debug: Logs that are used for interactive investigation during development. These logs should primarily contain information useful for debugging and have no long-term value. Information: Logs that track the general flow of the application. These logs should have long-term value. Warning: Logs that highlight an abnormal or unexpected event in the application flow, but do not otherwise cause the application execution to stop. Error: Logs that highlight when the current flow of execution is stopped due to a failure. These should indicate a failure in the current activity, not an application-wide failure. Critical: Logs that describe an unrecoverable application or system crash, or a catastrophic failure that requires immediate attention. Log exceptions with full details Exceptions should always be logged as exceptions (i.e. not only the exception message) so that the stacktrace and all other information is retained. Use the correct log level to distinguish crictial, erroneous and informational exceptions.\nLogger implementation Use concrete implementations only in the application root Use concrete implementations (e.g. Serilog types, etc.) only in the root of the application (e.g. Startup.cs of your ASP.NET Core app). All services and “logger consumers” should only use the ILogger, ILogger\u0026lt;T\u0026gt; or ILoggerFactory interface via (constructor) dependency injection. This way everything except the application bootstrapper is independent of the actual logger implementation and changing the logging sink is a no-brainer.\nConsider using Serilog for a stable ILogger implementation The ILogger (and ILoggerFactory) are quite generic and open interfaces with a lot of room about how to actually implement them. To show the problem, let’s have a look at the BeginScope method:\nIDisposable BeginScope\u0026amp;lt;TState\u0026gt;(TState state) As you can see, the state can be any object. The actual implementation has to deal with that somehow but each implementation might differ on how it handles them. If you pass a Dictionary\u0026lt;string, object\u0026gt; to Serilog’s ILogger implementation, then it adds all these key-value tuples as custom properties to all log statements in the scope.\nThat is why I recommend to use Serilog as an intermedate layer/abstraction between ILogger and the actual sink (e.g. Application Insights) and not directly use the Application Insights ILogger implementation. The reason for that is that the AI implementation might not support all features (e.g. scopes are not supported) and changing a sink will not change the behavior and feature set of the logger implementation.\nSample code to use Serilog and ILogger in an ASP.NET Core web app (UseSerilog() can be found in Serilog.AspNetCore):\npublic class Program { public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.Seq(\"http://localhost:5341\") .WriteTo.Console() .CreateLogger(); CreateWebHostBuilder(args) .UseSerilog() .Build() .Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) =\u0026amp;gt; WebHost.CreateDefaultBuilder(args) .UseStartup\u0026amp;amp;lt;Startup\u0026amp;gt;(); }\nSample code to use Serilog and ILogger in a console application (AddSerilog() can be found in Serilog.Extensions.Logging):\npublic class Program { public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.Seq(\"http://localhost:5341\") .WriteTo.Console() .CreateLogger(); new HostBuilder() .ConfigureServices((hostContext, services) =\u0026amp;gt; { services.AddHostedService\u0026amp;amp;lt;MyHostedService\u0026amp;gt;(); }) .ConfigureLogging((hostContext, logging) =\u0026amp;gt; { logging.AddSerilog(); }) .Build() .Run(); } }\nSetup for Application Insights without dependency injection Here you can see a simple setup code to initialize the Serilog logger with an Application Insights sink and then add this logger provider to the logger factory:\nPackages:\nMicrosoft.Extensions.Logging Microsoft.Extensions.Logging.Abstractions Serilog.Extensions.Logging Serilog.Sinks.Seq TelemetryConfiguration.Active.InstrumentationKey = instrumentationKey; var serilogLogger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override(\u0026ldquo;Microsoft\u0026rdquo;, LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.ApplicationInsightsTraces(TelemetryConfiguration.Active) .CreateLogger();\nvar loggerFactory = (ILoggerFactory)new LoggerFactory(); loggerFactory.AddSerilog(serilogLogger);\nNow you have a logger factory with which you can create new untyped loggers:\nvar logger = loggerFactory.CreateLogger(); … or typed loggers:\nvar logger = loggerFactory.CreateLogger\u0026amp;lt;MyService\u0026gt;(); In this case, the type is used to add the SourceContext custom property in Application Insights for filtering.\nInject ILogger or ILogger\u0026lt;T\u0026gt;, avoid injecting ILoggerFactory Prefer injecting the ILogger interface and if necessary the ILogger\u0026lt;T\u0026gt; interface. Ideally your class’ constructor requests an ILogger and the IoC framework creates an instance of an ILogger\u0026lt;T\u0026gt; where T is the requesting class.\nAvoid injecting ILoggerFactory because it would violate the SRP (single responsibilty principle) if a service creates child instances (there are exceptions where you need to do this).\nLibraries and logging Try to avoid logging in libraries Most libraries should not use logging but use regular control flow like return values, callbacks, events or exceptions. Consider using System.Diagnostics.Trace for debug logging.\nUse logging via dependency injection in library code .NET libraries which need to log, should only use the ILogger interface to communicate with the logging infrastructure. They should use it via (constructor) injection. Avoid using a static property/singleton because it would force all callers to use the same logging infrastructure.\nAssume you have a library which has a MyHttpClient class to communicate with a backend. The signature of its constructor should look like this:\npublic class MyHttpClient { private ILogger _logger; public MyHttpClient(string url, ILogger logger) { _logger = logger ?? NullLogger.Instance; } ... }\nOnly use logging abstractions in libraries In libraries you should only use the described logging abstractions and no concrete types because they are set up in the application root. This all implies that a .NET library should only have a dependency to Microsoft.Extensions.Logging.Abstractions for logging.\nFor more information about logging in libraries, I recommend reading Good citizenship – logging from .NET libraries\nTesting Use the null logger to ignore logs in tests Use NullLogger.Instance as null object in tests to avoid lots of null checks just for testing.\nUse Seq for local logging I recommend to use the Seq as a local development logging backend. You can easily run it via Docker and write local development logs to it. This way you can better access and browse logs than with plain text files.\nJust start a local Seq image:\ndocker run -d --restart unless-stopped --name seq -e ACCEPT_EULA=Y -p 5341:80 datalust/seq:latest And add Seq as a Serilog logging sink:\nvar serilogLogger = new LoggerConfiguration() .WriteTo.Seq(\"http://localhost:5341\") .CreateLogger(); var loggerFactory = (ILoggerFactory)new LoggerFactory(); loggerFactory.AddSerilog(serilogLogger);\nvar logger = loggerFactory.CreateLogger();\nNow you can browse to http://localhost:5341 to access the local logging UI.\nOriginal article can be found here: https://blog.rsuter.com/logging-with-ilogger-recommendations-and-best-practices/\nFurther reading Stephen Cleary – Microsoft.Extensions.Logging, Part 1: Introduction Stephen Cleary – Microsoft.Extensions.Logging, Part 2: Types ","date":"23 April 2021","externalUrl":null,"permalink":"/ilogger-in-net-best-practices/","section":"Articles","summary":"If you are like me you will have been using ILogger in DotNet Core for some time, but you’ll have noticed there are many ways to use the logger, I found this useful article by Rico Suter going over some recommendation and best practices.\n","title":"ILogger in .NET: best practices","type":"articles"},{"content":"Here are various was to convert enums to a lists\nOriginal posting Get a List of Enum Members The idea is to use Enum.GetValues() method to get an array of the values of the constants in the enum. To get an IEnumerable\u0026lt;T\u0026gt; of all the values in the enum, call Cast\u0026lt;T\u0026gt;() on the array. To get a list, call ToList() after casting.\nusing System; using System.Linq; using System.Collections.Generic; public class Example { public enum Days { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7 }\npublic static void Main() { List\u0026amp;amp;lt;Days\u0026amp;gt; days = Enum.GetValues(typeof(Days)) .Cast\u0026amp;amp;lt;Days\u0026amp;gt;() .ToList(); Console.WriteLine(String.Join(Environment.NewLine, days)); } }\n/* Output:\nMonday Tuesday Wednesday Thursday Friday Saturday Sunday */ Get an Array of Enum Members Instead of using LINQ’s Cast\u0026lt;T\u0026gt;() method, we can cast the array returned by the Enum.GetValues() method as shown below. Following solution returns an array instead of List.\nusing System; public class Example { public enum Days { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7 }\npublic static void Main() { Days[] days = (Days[])Enum.GetValues(typeof(Days)); Console.WriteLine(String.Join(Environment.NewLine, days)); } }\n/* Output:\nMonday Tuesday Wednesday Thursday Friday Saturday Sunday */ Get a List of Enum members with their constant values To get List of enum members with their associated constant values, you can use LINQ’s Select() method as demonstrated below:\nusing System; using System.Linq; using System.Collections.Generic; public class Example { public enum Days { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7 }\npublic static void Main() { var days = Enum.GetValues(typeof(Days)) .Cast\u0026amp;amp;lt;Days\u0026amp;gt;() .Select(d =\u0026amp;gt; (d, (int)d)) .ToList(); Console.WriteLine(String.Join(Environment.NewLine, days)); } }\n/* Output:\n(Monday, 1) (Tuesday, 2) (Wednesday, 3) (Thursday, 4) (Friday, 5) (Saturday, 6) (Sunday, 7) */ Get a Dictionary of Enum members with their constant values To get a Dictionary of enum members with their associated constant values, you can use LINQ’s ToDictionary() method as demonstrated below:\nusing System; using System.Linq; using System.Collections.Generic; public class Example { public enum Days { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7 }\npublic static void Main() { Dictionary\u0026amp;amp;lt;string, int\u0026amp;gt; days = Enum.GetValues(typeof(Days)) .Cast\u0026amp;amp;lt;Days\u0026amp;gt;() .ToDictionary(k =\u0026amp;gt; k.ToString(), v =\u0026amp;gt; (int)v); Console.WriteLine(String.Join(Environment.NewLine, days)); } }\n/* Output:\n[Monday, 1] [Tuesday, 2] [Wednesday, 3] [Thursday, 4] [Friday, 5] [Saturday, 6] [Sunday, 7] */ ","date":"1 March 2021","externalUrl":null,"permalink":"/convert-an-enum-to-a-list/","section":"Articles","summary":"Here are various was to convert enums to a lists\nOriginal posting Get a List of Enum Members The idea is to use Enum.GetValues() method to get an array of the values of the constants in the enum. To get an IEnumerable\u003cT\u003e of all the values in the enum, call Cast\u003cT\u003e() on the array. To get a list, call ToList() after casting.\n","title":"Convert an enum to a list","type":"articles"},{"content":"","date":"10 February 2021","externalUrl":null,"permalink":"/categories/sql/","section":"Categories","summary":"","title":"SQL","type":"categories"},{"content":"The fastest way to perform a SQL record count is:\nDECLARE @TableName sysname SET @TableName = 'Log' SELECT TBL.object_id, TBL.name, SUM(PART.rows) AS rows FROM sys.tables TBL INNER JOIN sys.partitions PART ON TBL.object_id = PART.object_id INNER JOIN sys.indexes IDX ON PART.object_id = IDX.object_id AND PART.index_id = IDX.index_id WHERE TBL.name = @TableName AND IDX.index_id \u0026amp;lt; 2 GROUP BY TBL.object_id, TBL.name; ","date":"10 February 2021","externalUrl":null,"permalink":"/sql-record-count/","section":"Articles","summary":"The fastest way to perform a SQL record count is:\nDECLARE @TableName sysname SET @TableName = 'Log' SELECT TBL.object_id, TBL.name, SUM(PART.rows) AS rows FROM sys.tables TBL INNER JOIN sys.partitions PART ON TBL.object_id = PART.object_id INNER JOIN sys.indexes IDX ON PART.object_id = IDX.object_id AND PART.index_id = IDX.index_id WHERE TBL.name = @TableName AND IDX.index_id \u0026lt; 2 GROUP BY TBL.object_id, TBL.name; ","title":"SQL Record Count","type":"articles"},{"content":"I love this smart template generator, saves so much time and effort.\nGenerates a unit test boilerplate from a given C# class, setting up mocks for all dependencies. Right click an item in Solution Explorer and choose “Create Unit Test Boilerplate” . Supports Visual Studio Test, NUnit, xUnit and many mock frameworks.\nhttps://marketplace.visualstudio.com/items?itemName=RandomEngy.UnitTestBoilerplateGenerator\n","date":"25 January 2021","externalUrl":null,"permalink":"/unit-test-boilerplate-generator/","section":"Articles","summary":"I love this smart template generator, saves so much time and effort.\nGenerates a unit test boilerplate from a given C# class, setting up mocks for all dependencies. Right click an item in Solution Explorer and choose “Create Unit Test Boilerplate” . Supports Visual Studio Test, NUnit, xUnit and many mock frameworks.\n","title":"Unit Test Boilerplate Generator","type":"articles"},{"content":"","date":"25 January 2021","externalUrl":null,"permalink":"/categories/unit-testing/","section":"Categories","summary":"","title":"Unit Testing","type":"categories"},{"content":"As defined by Polly “A circuit breaker detects the level of faults in calls placed through it, and prevents calls when a configurable fault threshold is exceeded”.\nThe circuit breaker only makes sense when calling a less reliable API.\nWait \u0026amp; Retry will only try on the following HTTP Status codes:\nHttpStatusCode.InternalServerError, HttpStatusCode.BadGateway, HttpStatusCode.GatewayTimeout, HttpStatusCode.RequestTimeout, HttpStatusCode.Forbidden, HttpStatusCode.PaymentRequired, HttpStatusCode.TooManyRequests, HttpStatusCode.Unauthorized When a method fails several times in a row, the application should use the fast failure method. For example, if the API cannot be used multiple times in a row and is likely to fail, repeated calls to the API are useless.\nIf you find the method call you are calling is delayed, and this is very reasonable, you will have to use fallback scenario. The circuit breaker tracks the number of failed API calls. Once it continuously exceeds the failure threshold number, it will not even try to call the API for subsequent requests. Instead, it will fail immediately, just like the API failed. After the timeout, the circuit breaker will make a method call to “test” the API and see if it succeeded. If it fails, it returns immediate failure. If successful, the circuit is closed again, and it will return to call the API for each request.\nCircuit-breaker is a state machine\nA circuit-breaker is best thought of as a state machine, with three main states.\nClose – Normal operations\nOpen – Failing no traffic returns a 500\nHalf Open – Trial period\nIn this trial period:\nIf a handled exception is received, that exception is rethrown, and the circuit transitions immediately back to open, and remains open again for the configured timespan.\nIf a successful result is received, the circuit transitions back to closed.\nIf an unhandled exception is received, the circuit remains in half-open.\nFor full details on the Circuit Break please go to Polly directly, here is the link:\nhttps://github.com/App-vNext/Polly/wiki/Circuit-Breaker\nCircuitBreaker.drawioDownload https://app.diagrams.net/\n","date":"15 January 2021","externalUrl":null,"permalink":"/circuit-breaker/","section":"Articles","summary":"As defined by Polly “A circuit breaker detects the level of faults in calls placed through it, and prevents calls when a configurable fault threshold is exceeded”.\nThe circuit breaker only makes sense when calling a less reliable API.\n","title":"Circuit Breaker","type":"articles"},{"content":"What is a Resilience Framework? Polly is classed as a resilience framework. A resilience framework is a set of libraries that help an application to recover from transient or more extended failures in services or infrastructure upon which it depends. When recovery is not possible, the resilience framework will facilitate graceful degradation of your application.\nPolly has been around for many years and has been tried and tested in many applications\nhttp://www.thepollyproject.org/\nThe source code for Polly can be found on GitHub here:\nhttps://github.com/App-vNext/Polly\nStrategies – how to deal with the problems There are a number of reactive approaches we can take with Polly:\nRetry policy. This immediately retries the request some specified number of times without any delay. Wait and Retry policy introduces a delay before each retry,\nCircuit Breaker will stop all requests to an endpoint if some failure threshold is reached\nFallback returns some specified default if the request fails. Fallback is often used in conjunction with other policies. For example, if a request fails, retry it. If the retries fail, return a default with the Fallback. Caching for a faster response and better performance.\nThese different processes assist when your application is suffering from a problem it can not address, like a request failure and a timeout, and you need to take some immediate action to address the issue. Delegates can also be used with these policies, allowing you to run custom code as part of the policy. Bulkhead Isolation to handle slow responding external services and prevents overloading, deals with resource allocation has the ability to trigger scaling and deals with load shedding (when your application stops returning requests and fails).\nBulkhead Isolation The bulkhead isolation is a proactive policy allow you to keep your application up and running during heavy overloading to keep your application available. This policy can also be used for resource sharing, load shedding or as a trigger for horizontal scaling.\nBuilds a bulkhead isolation Polly.Policy, which limits the maximum concurrency of actions executed through the policy. Imposing a maximum concurrency limits the potential of governed actions, when faulting, to bring down the system.\nWhen an execution would cause the number of actions executing concurrently through the policy to exceed maxParallelization, the policy allows a further maxQueuingActions executions to queue, waiting for a concurrent execution slot. When an execution would cause the number of queuing actions to exceed maxQueuingActions, a Polly.Bulkhead.BulkheadRejectedException is thrown.\nThe Bulkhead Isolation has two parameters and an optional delegate.\nmaxParallelization: The maximum number of concurrent actions that may be executed through the policy.\nmaxQueuingActions: The maximum number of actions that may be queued, waiting for an execution slot.\nonBulkheadRejectedAsync: An action to call asynchronously if the bulkhead rejects execution due to oversubscription.\nWhen the load increases the Parallelization (execution slots get populated), when they are full then the requests fill the QueuingActions slots, when these get filled then a 500 exception is returned.\nHere is an example of how to instantiate the Bulkhead policy with 2 execution slots and 4 queue slots\nBulkheadPolicy\u0026lt;HttpResponseMessage\u0026gt; bulkheadIsolationPolicy = Policy.BulkheadAsync\u0026lt;HttpResponseMessage\u0026gt;(2, 4, onBulkheadRejectedAsync: OnBulkheadRejectedAsync); For best practice when using Polly, this will depend on your need and requirements. However, i’d recommend using the Http Client Factory, as this makes coding so much easier and more flexible and so much cleaner.\nHere is a simple example of using the http Client Factory:\nAs you can see no sign of Polly.\nEverything is setup at StartUp, like this:\nYou can then add the polly policy to the Http Client:\nIdeally, we would have a Polly for each different HTTP verbs or even for individual endpoints, to do this we need to set up a Polly Registry\nSource can be found on GitHub\nhttps://github.com/BryanAvery/PollyHttpClientFactory\nGood source of reference is this post:\nhttps://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory\nhttps://www.twilio.com/blog/polly-fallbacks-dot-net-service-communication\n","date":"9 November 2020","externalUrl":null,"permalink":"/fault-tolerance-using-polly/","section":"Articles","summary":"What is a Resilience Framework? Polly is classed as a resilience framework. A resilience framework is a set of libraries that help an application to recover from transient or more extended failures in services or infrastructure upon which it depends. When recovery is not possible, the resilience framework will facilitate graceful degradation of your application.\n","title":"Fault tolerance using Polly","type":"articles"},{"content":"Throttling and rate-limiting allow you to prevent abuse of your API and ensure that your API withstands large numbers of calls (including DoS and accidental loops). With Throttling, you can set a delay on calls after an SLA tier has been exceeded, slowing down the number of requests an API client is making.\nRate limiting lets you set a hard number for how many calls the client may make in a specific time frame. Essentially, if a client is making too many calls, you can slow down the responses or cut the client off to prevent the system from being overrun or disrupting your other users.\nThis is especially helpful in negating malicious attacks, as well as the dreaded accidental infinite loop that pounds your API with calls. While this practice may seem harsh at first, it is widely adopted to ensure the best quality of service for everyone.\nAspNetCoreRateLimit is an ASP.NET Core rate limiting solution designed to control the rate of requests that clients can make to a Web API or MVC app based on IP address or client ID. The AspNetCoreRateLimit package contains an IpRateLimitMiddleware and a ClientRateLimitMiddleware, with each middleware you can set multiple limits for different scenarios like allowing an IP or Client to make a maximum number of calls in a time interval like per second, 15 minutes, etc. You can define these limits to address all requests made to an API, or you can scope the limits to each API URL or HTTP verb and path.\nDefault AppSetting.json we use for My MoD API Gateway:\n“IpRateLimiting”: {\n“EnableEndpointRateLimiting”: true,\n“StackBlockedRequests”: false,\n“RealIPHeader”: “X-Real-IP”,\n“ClientIdHeader”: “X-ClientId”,\n“HttpStatusCode”: 429,\n“GeneralRules”: [\n{\n“Endpoint”: “*:/api/*”,\n“Period”: “1s”,\n“Limit”: 300\n}\n]\n},\nEnableEndpointRateLimiting is set to true, then the limits will apply for each endpoint as in {HTTP_Verb}{PATH} StackBlockedRequests is set to false, rejected calls are not added to the throttle counter. If a client makes 3 requests per second and you’ve set a limit of one call per second, other limits like per minute or per day counters will only record the first call, the one that wasn’t blocked. RealIpHeader is used to extract the client IP when your Kestrel server is behind a reverse proxy, if the proxy uses a different header then X-Real-IP use this option to set it up. ClientIdHeader is used to extract the client id for whitelisting. If a client id is present in this header and matches a value specified in ClientWhitelist then no rate limits are applied. HttpStatusCode that is returned if the limit is reached.\nDefining rate limit rules A rule is composed of an endpoint, a period and a limit.\nEndpoint format is {HTTP_Verb}:{PATH}, you can target any HTTP verb by using the asterisk symbol.\nPeriod format is {INT}{PERIOD_TYPE}, you can use one of the following period types: s, m, h, d.\nLimit format is {LONG}.\n","date":"12 August 2020","externalUrl":null,"permalink":"/throttling-rate-limiter-for-an-api/","section":"Articles","summary":"Throttling and rate-limiting allow you to prevent abuse of your API and ensure that your API withstands large numbers of calls (including DoS and accidental loops). With Throttling, you can set a delay on calls after an SLA tier has been exceeded, slowing down the number of requests an API client is making.\n","title":"Throttling/Rate Limiter for an API","type":"articles"},{"content":"I came across a very good article on ASP.NET Core which I needed to bookmark, as it gives a clear and understandable guidance on keeping things working as efficiently as possible.\nhttps://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AspNetCoreGuidance.md\nHere is a copy of the post\nTable of contents ASP.NET Core Guidance Avoid using synchronous Read/Write overloads on HttpRequest.Body and HttpResponse.Body Prefer using HttpRequest.ReadAsFormAsync() over HttpRequest.Form Use buffered and synchronous reads and writes as an alternative to asynchronous reading and writing Avoid reading large request bodies or response bodies into memory Do not store IHttpContextAccessor.HttpContext in a field Do not access the HttpContext from multiple threads in parallel. It is not thread safe. Do not use the HttpContext after the request is complete Do not capture the HttpContext in background threads Do not capture services injected into the controllers on background threads Avoid adding headers after the HttpResponse has started ASP.NET Core Guidance ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-based, Internet-connected applications. This guide captures some of the common pitfalls and practices when writing scalable server applications.\nAvoid using synchronous Read/Write overloads on HttpRequest.Body and HttpResponse.Body All IO in ASP.NET Core is asynchronous. Servers implement the Stream interface which has both synchronous and asynchronous overloads. The asynchronous ones should be preferred to avoid blocking thread pool threads (this could lead to thread pool starvation).\n❌ BAD This example uses the StreamReader.ReadToEnd and as a result blocks the current thread to wait for the result. This is an example of sync over async.\n“`C#\npublic class MyController : Controller\n{\n[HttpGet(“/pokemon”)]\npublic ActionResult Get()\n{\n// This synchronously reads the entire http request body into memory.\n// If the client is slowly uploading, we’re doing sync over async because Kestrel does NOT support synchronous reads.\nvar json = new StreamReader(Request.Body).ReadToEnd();\nreturn JsonConvert.DeserializeObject\u0026amp;lt;PokemonData\u0026gt;(json); } }\n:white_check_mark: **GOOD** This example uses `StreamReader.ReadToEndAsync` and as a result, does not block the thread while reading. public class MyController : Controller { [HttpGet(\u0026#34;/pokemon\u0026#34;)] public async Task\u0026amp;amp;lt;ActionResult\u0026amp;amp;lt;PokemonData\u0026amp;gt;\u0026amp;gt; Get() { // This asynchronously reads the entire http request body into memory. var json = await new StreamReader(Request.Body).ReadToEndAsync(); return JsonConvert.DeserializeObject\u0026amp;amp;lt;PokemonData\u0026amp;gt;(json); } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;:bulb:\u0026lt;strong\u0026gt;NOTE: If the request is large it could lead to out of memory problems which can result in a Denial Of Service. See \u0026lt;a href=\u0026#34;/index.html%3Fp=1424.html#avoid-reading-large-request-bodies-or-response-bodies-into-memory\u0026#34;\u0026gt;this\u0026lt;/a\u0026gt; for more information.\u0026lt;/strong\u0026gt;\u0026lt;/p\u0026gt; \u0026lt;h2\u0026gt;Prefer using HttpRequest.ReadAsFormAsync() over HttpRequest.Form\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;You should always prefer \u0026lt;code\u0026gt;HttpRequest.ReadAsFormAsync()\u0026lt;/code\u0026gt; over \u0026lt;code\u0026gt;HttpRequest.Form\u0026lt;/code\u0026gt;. The only time it is safe to use \u0026lt;code\u0026gt;HttpRequest.Form\u0026lt;/code\u0026gt; is the form has already been read by a call to \u0026lt;code\u0026gt;HttpRequest.ReadAsFormAsync()\u0026lt;/code\u0026gt; and the cached form value is being read using \u0026lt;code\u0026gt;HttpRequest.Form\u0026lt;/code\u0026gt;.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This example uses HttpRequest.Form uses \u0026lt;a href=\u0026#34;https://bryanavery.co.uk/asp-net-core-guidance/AsyncGuidance.md#avoid-using-taskresult-and-taskwait\u0026#34;\u0026gt;sync over async\u0026lt;/a\u0026gt; under the covers and can lead to thread pool starvation (in some cases).\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public class MyController : Controller\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;[HttpPost(“/form-body”)]\u0026lt;br/\u0026gt;public IActionResult Post()\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;var form = HttpRequest.Form;\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; Process(form[\u0026#34;id\u0026#34;], form[\u0026#34;name\u0026#34;]); return Accepted(); } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example uses `HttpRequest.ReadAsFormAsync()` to read the form body asynchronously. ```C# public class MyController : Controller { [HttpPost(\u0026#34;/form-body\u0026#34;)] public async Task\u0026amp;amp;lt;IActionResult\u0026amp;gt; Post() { var form = await HttpRequest.ReadAsFormAsync(); Process(form[\u0026#34;id\u0026#34;], form[\u0026#34;name\u0026#34;]); return Accepted(); } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Avoid reading large request bodies or response bodies into memory\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;In .NET any single object allocation greater than 85KB ends up in the large object heap (\u0026lt;a href=\u0026#34;https://blogs.msdn.microsoft.com/maoni/2006/04/19/large-object-heap/\u0026#34;\u0026gt;LOH\u0026lt;/a\u0026gt;). Large objects are expensive in 2 ways:\u0026lt;/p\u0026gt; \u0026lt;ul\u0026gt;\u0026lt;li\u0026gt;The allocation cost is high because the memory for a newly allocated large object has to be cleared (the CLR guarantees that memory for all newly allocated objects is cleared)\u0026lt;/li\u0026gt;\u0026lt;li\u0026gt;LOH is collected with the rest of the heap (it requires a “full garbage collection” or Gen2 collection)\u0026lt;/li\u0026gt;\u0026lt;/ul\u0026gt; \u0026lt;p\u0026gt;This \u0026lt;a href=\u0026#34;https://adamsitnik.com/Array-Pool/#the-problem\u0026#34;\u0026gt;blog post\u0026lt;/a\u0026gt; describes the problem succinctly:\u0026lt;/p\u0026gt; \u0026lt;blockquote class=\u0026#34;is-layout-flow\u0026#34;\u0026gt;\u0026lt;p\u0026gt;When a large object is allocated, it’s marked as Gen 2 object. Not Gen 0 as for small objects. The consequences are that if you run out of memory in LOH, GC cleans up whole managed heap, not only LOH. So it cleans up Gen 0, Gen 1 and Gen 2 including LOH. This is called full garbage collection and is the most time-consuming garbage collection. For many applications, it can be acceptable. But definitely not for high-performance web servers, where few big memory buffers are needed to handle an average web request (read from a socket, decompress, decode JSON \u0026amp;amp; more).\u0026lt;/p\u0026gt;\u0026lt;/blockquote\u0026gt; \u0026lt;p\u0026gt;Naively storing a large request or response body into a single \u0026lt;code\u0026gt;byte[]\u0026lt;/code\u0026gt; or \u0026lt;code\u0026gt;string\u0026lt;/code\u0026gt; may result in quickly running out of space in the LOH and may cause performance issues for your application because of full GCs running.\u0026lt;/p\u0026gt; \u0026lt;h2\u0026gt;Use buffered and synchronous reads and writes as an alternative to asynchronous reading and writing\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;When using a serializer/de-serializer that only supports synchronous reads and writes (like JSON.NET) then prefer buffering the data into memory before passing data into the serializer/de-serializer.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;:bulb:\u0026lt;strong\u0026gt;NOTE: If the request is large it could lead to out of memory problems which can result in a Denial Of Service. See \u0026lt;a href=\u0026#34;/index.html%3Fp=1424.html#avoid-reading-large-request-bodies-or-response-bodies-into-memory\u0026#34;\u0026gt;this\u0026lt;/a\u0026gt; for more information.\u0026lt;/strong\u0026gt;\u0026lt;/p\u0026gt; \u0026lt;h2\u0026gt;Do not store IHttpContextAccessor.HttpContext in a field\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;The \u0026lt;code\u0026gt;IHttpContextAccessor.HttpContext\u0026lt;/code\u0026gt; will return the \u0026lt;code\u0026gt;HttpContext\u0026lt;/code\u0026gt; of the active request when accessed from the request thread. It should not be stored in a field or variable.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This example stores the HttpContext in a field then attempts to use it later.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public class MyType\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;private readonly HttpContext _context;\u0026lt;br/\u0026gt;public MyType(IHttpContextAccessor accessor)\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;_context = accessor.HttpContext;\u0026lt;br/\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; public void CheckAdmin() { if (!_context.User.IsInRole(\u0026#34;admin\u0026#34;)) { throw new UnauthorizedAccessException(\u0026#34;The current user isn\u0026#39;t an admin\u0026#34;); } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; The above logic will likely capture a null or bogus HttpContext in the constructor for later use. :white_check_mark: **GOOD** This example stores the IHttpContextAccesor itself in a field and uses the HttpContext field at the correct time (checking for null). ```C# public class MyType { private readonly IHttpContextAccessor _accessor; public MyType(IHttpContextAccessor accessor) { _accessor = accessor; } public void CheckAdmin() { var context = _accessor.HttpContext; if (context != null \u0026amp;amp;amp;\u0026amp;amp;amp; !context.User.IsInRole(\u0026#34;admin\u0026#34;)) { throw new UnauthorizedAccessException(\u0026#34;The current user isn\u0026#39;t an admin\u0026#34;); } } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Do not access the HttpContext from multiple threads in parallel. It is not thread safe.\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;The \u0026lt;code\u0026gt;HttpContext\u0026lt;/code\u0026gt; is \u0026lt;em\u0026gt;NOT\u0026lt;/em\u0026gt; threadsafe. Accessing it from multiple threads in parallel can cause corruption resulting in undefined behavior (hangs, crashes, data corruption).\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This example makes 3 parallel requests and logs the incoming request path before and after the outgoing http request. This accesses the request path from multiple threads potentially in parallel.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public class AsyncController : Controller\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;[HttpGet(“/search”)]\u0026lt;br/\u0026gt;public async Task Get(string query)\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;var query1 = SearchAsync(SearchEngine.Google, query);\u0026lt;br/\u0026gt;var query2 = SearchAsync(SearchEngine.Bing, query);\u0026lt;br/\u0026gt;var query3 = SearchAsync(SearchEngine.DuckDuckGo, query);\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; await Task.WhenAll(query1, query2, query3); var results1 = await query1; var results2 = await query2; var results3 = await query3; return SearchResults.Combine(results1, results2, results3); } private async Task\u0026amp;amp;lt;SearchResults\u0026amp;gt; SearchAsync(SearchEngine engine, string query) { var searchResults = SearchResults.Empty; try { _logger.LogInformation(\u0026#34;Starting search query from {path}.\u0026#34;, HttpContext.Request.Path); searchResults = await _searchService.SearchAsync(engine, query); _logger.LogInformation(\u0026#34;Finishing search query from {path}.\u0026#34;, HttpContext.Request.Path); } catch (Exception ex) { _logger.LogError(ex, \u0026#34;Failed query from {path}\u0026#34;, HttpContext.Request.Path); } return searchResults; } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example copies all data from the incoming request before making the 3 parallel requests. ```C# public class AsyncController : Controller { [HttpGet(\u0026#34;/search\u0026#34;)] public async Task\u0026amp;amp;lt;SearchResults\u0026amp;gt; Get(string query) { string path = HttpContext.Request.Path; var query1 = SearchAsync(SearchEngine.Google, query, path); var query2 = SearchAsync(SearchEngine.Bing, query, path); var query3 = SearchAsync(SearchEngine.DuckDuckGo, query, path); await Task.WhenAll(query1, query2, query3); var results1 = await query1; var results2 = await query2; var results3 = await query3; return SearchResults.Combine(results1, results2, results3); } private async Task\u0026amp;amp;lt;SearchResults\u0026amp;gt; SearchAsync(SearchEngine engine, string query, string path) { var searchResults = SearchResults.Empty; try { _logger.LogInformation(\u0026#34;Starting search query from {path}.\u0026#34;, path); searchResults = await _searchService.SearchAsync(engine, query); _logger.LogInformation(\u0026#34;Finishing search query from {path}.\u0026#34;, path); } catch (Exception ex) { _logger.LogError(ex, \u0026#34;Failed query from {path}\u0026#34;, path); } return searchResults; } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Do not use the HttpContext after the request is complete\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;The \u0026lt;code\u0026gt;HttpContext\u0026lt;/code\u0026gt; is only valid as long as there is an active http request in flight. The entire ASP.NET Core pipeline is an asynchronous chain of delegates that executes every request. When the \u0026lt;code\u0026gt;Task\u0026lt;/code\u0026gt; returned from this chain completes, the \u0026lt;code\u0026gt;HttpContext\u0026lt;/code\u0026gt; is recycled.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This example uses async void (which is a \u0026lt;strong\u0026gt;ALWAYS\u0026lt;/strong\u0026gt; bad in ASP.NET Core applications) and as a result, accesses the \u0026lt;code\u0026gt;HttpResponse\u0026lt;/code\u0026gt; after the http request is complete. It will crash the process as a result.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public class AsyncVoidController : Controller\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;[HttpGet(“/async”)]\u0026lt;br/\u0026gt;public async void Get()\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;await Task.Delay(1000);\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; // THIS will crash the process since we\u0026#39;re writing after the response has completed on a background thread await Response.WriteAsync(\u0026#34;Hello World\u0026#34;); } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example returns a `Task` to the framework so the http request doesn\u0026#39;t complete until the entire action completes. ```C# public class AsyncController : Controller { [HttpGet(\u0026#34;/async\u0026#34;)] public async Task Get() { await Task.Delay(1000); await Response.WriteAsync(\u0026#34;Hello World\u0026#34;); } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Do not capture the HttpContext in background threads\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This example shows a closure is capturing the HttpContext from the Controller property. This is bad because this work item could run\u0026lt;br/\u0026gt;outside of the request scope and as a result, could lead to reading a bogus HttpContext.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;[HttpGet(“/fire-and-forget-1”)]\u0026lt;br/\u0026gt;public IActionResult FireAndForget1()\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;_ = Task.Run(() =\u0026amp;gt;\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;await Task.Delay(1000);\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; // This closure is capturing the context from the Controller property. This is bad because this work item could run // outside of the http request leading to reading of bogus data. var path = HttpContext.Request.Path; Log(path); }); return Accepted(); \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example copies the data required in the background task during the request explictly and does not reference anything from the controller itself. ```C# [HttpGet(\u0026#34;/fire-and-forget-3\u0026#34;)] public IActionResult FireAndForget3() { string path = HttpContext.Request.Path; _ = Task.Run(async () =\u0026amp;gt; { await Task.Delay(1000); // This captures just the path Log(path); }); return Accepted(); } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Do not capture services injected into the controllers on background threads\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This example shows a closure is capturing the DbContext from the Controller action parameter. This is bad because this work item could run\u0026lt;br/\u0026gt;outside of the request scope and the PokemonDbContext is scoped to the request. As a result, this will end up with an ObjectDisposedException.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;[HttpGet(“/fire-and-forget-1”)]\u0026lt;br/\u0026gt;public IActionResult FireAndForget1([FromServices]PokemonDbContext context)\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;_ = Task.Run(() =\u0026amp;gt;\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;await Task.Delay(1000);\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; // This closure is capturing the context from the Controller action parameter. This is bad because this work item could run // outside of the request scope and the PokemonDbContext is scoped to the request. As a result, this throw an ObjectDisposedException context.Pokemon.Add(new Pokemon()); await context.SaveChangesAsync(); }); return Accepted(); \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example injects an `IServiceScopeFactory` and creates a new dependency injection scope in the background thread and does not reference anything from the controller itself. ```C# [HttpGet(\u0026#34;/fire-and-forget-3\u0026#34;)] public IActionResult FireAndForget3([FromServices]IServiceScopeFactory serviceScopeFactory) { // This version of fire and forget adds some exception handling. We\u0026#39;re also no longer capturing the PokemonDbContext from the incoming request. // Instead, we\u0026#39;re injecting an IServiceScopeFactory (which is a singleton) in order to create a scope in the background work item. _ = Task.Run(async () =\u0026amp;gt; { await Task.Delay(1000); // Create a scope for the lifetime of the background operation and resolve services from it using (var scope = serviceScopeFactory.CreateScope()) { // This will a PokemonDbContext from the correct scope and the operation will succeed var context = scope.ServiceProvider.GetRequiredService\u0026amp;amp;lt;PokemonDbContext\u0026amp;gt;(); context.Pokemon.Add(new Pokemon()); await context.SaveChangesAsync(); } }); return Accepted(); } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Avoid adding headers after the HttpResponse has started\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;ASP.NET Core does not buffer the http response body. This means that the very first time the response is written, the headers are sent along with that chunk of the body to the client. When this happens, it’s no longer possible to change response headers.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This logic tries to add response headers after the response has already started.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;app.Use(async (next, context) =\u0026amp;gt;\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;await context.Response.WriteAsync(“Hello “);\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; await next(); // This may fail if next() already wrote to the response context.Response.Headers[\u0026#34;test\u0026#34;] = \u0026#34;value\u0026#34;; \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;});\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example checks if the http response has started before writing to the body. ```C# app.Use(async (next, context) =\u0026amp;gt; { await context.Response.WriteAsync(\u0026#34;Hello \u0026#34;); await next(); // Check if the response has already started before adding header and writing if (!context.Response.HasStarted) { context.Response.Headers[\u0026#34;test\u0026#34;] = \u0026#34;value\u0026#34;; } }); \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;:white_check_mark: \u0026lt;strong\u0026gt;GOOD\u0026lt;/strong\u0026gt; This examples uses \u0026lt;code\u0026gt;HttpResponse.OnStarting\u0026lt;/code\u0026gt; to set the headers before the response headers are flushed to the client.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;It allows you to register a callback that will be invoked just before response headers are written to the client. It gives you the ability to append or override headers just in time, without requiring knowledge of the next middleware in the pipeline.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;app.Use(async (next, context) =\u0026amp;gt;\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;// Wire up the callback that will fire just before the response headers are sent to the client.\u0026lt;br/\u0026gt;context.Response.OnStarting(() =\u0026amp;gt;\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;context.Response.Headers[“someheader”] = “somevalue”;\u0026lt;br/\u0026gt;return Task.CompletedTask;\u0026lt;br/\u0026gt;});\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; await next(); \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;});\u0026lt;/p\u0026gt; ","date":"30 June 2020","externalUrl":null,"permalink":"/asp-net-core-guidance/","section":"Articles","summary":"I came across a very good article on ASP.NET Core which I needed to bookmark, as it gives a clear and understandable guidance on keeping things working as efficiently as possible.\nhttps://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AspNetCoreGuidance.md\nHere is a copy of the post\n","title":"ASP.NET Core Guidance","type":"articles"},{"content":"","date":"30 June 2020","externalUrl":null,"permalink":"/categories/async/","section":"Categories","summary":"","title":"Async","type":"categories"},{"content":"There is a right way and a wrong way with programme Asynchronously, mainly due to the initial way Microsoft brought in Async programming was not best practise and they have now made changes to make it more effective and be more productive.\nThis article by David Fowl give a very good explanation of the good ways to write Asynchronous programming.\nhttps://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md Here is the content from the post\nTable of contents Asynchronous Programming Asynchrony is viral Async void Prefer Task.FromResult over Task.Run for pre-computed or trivially computed data Avoid using Task.Run for long running work that blocks the thread Avoid using Task.Result and Task.Wait Prefer await over ContinueWith Always create TaskCompletionSource\u0026lt;T\u0026gt; with TaskCreationOptions.RunContinuationsAsynchronously Always dispose CancellationTokenSource(s) used for timeouts Always flow CancellationToken(s) to APIs that take a CancellationToken Cancelling uncancellable operations Always call FlushAsync on StreamWriter(s) or Stream(s) before calling Dispose Prefer async/await over directly returning Task ConfigureAwait Scenarios Timer callbacks Implicit async void delegates ConcurrentDictionary.GetOrAdd Constructors WindowsIdentity.RunImpersonated Asynchronous Programming Asynchronous programming has been around for several years on the .NET platform but has historically been very difficult to do well. Since the introduction of async/await\nin C# 5 asynchronous programming has become mainstream. Modern frameworks (like ASP.NET Core) are fully asynchronous and it’s very hard to avoid the async keyword when writing\nweb services. As a result, there’s been lots of confusion on the best practices for async and how to use it properly. This section will try to lay out some guidance with examples of bad and good patterns of how to write asynchronous code.\nAsynchrony is viral Once you go async, all of your callers SHOULD be async, since efforts to be async amount to nothing unless the entire callstack is async. In many cases, being partially async can be worse than being entirely synchronous. Therefore it is best to go all in, and make everything async at once.\n❌ BAD This example uses the Task.Result and as a result blocks the current thread to wait for the result. This is an example of sync over async.\n“`C#\npublic int DoSomethingAsync()\n{\nvar result = CallDependencyAsync().Result;\nreturn result + 1;\n}\n\u0026#x2705; GOOD This example uses the await keyword to get the result from CallDependencyAsync.\npublic async Task\u0026amp;amp;lt;int\u0026amp;gt; DoSomethingAsync() { var result = await CallDependencyAsync(); return result + 1; } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Async void\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;Use of async void in ASP.NET Core applications is \u0026lt;strong\u0026gt;ALWAYS\u0026lt;/strong\u0026gt; bad. Avoid it, never do it. Typically, it’s used when developers are trying to implement fire and forget patterns triggered by a controller action. Async void methods will crash the process if an exception is thrown. We’ll look at more of the patterns that cause developers to do this in ASP.NET Core applications but here’s a simple example:\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; Async void methods can’t be tracked and therefore unhandled exceptions can result in application crashes.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public class MyController : Controller\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;[HttpPost(“/start”)]\u0026lt;br/\u0026gt;public IActionResult Post()\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;BackgroundOperationAsync();\u0026lt;br/\u0026gt;return Accepted();\u0026lt;br/\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; public async void BackgroundOperationAsync() { var result = await CallDependencyAsync(); DoSomething(result); } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** `Task`-returning methods are better since unhandled exceptions trigger the [`TaskScheduler.UnobservedTaskException`](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskscheduler.unobservedtaskexception?view=netframework-4.7.2). ```C# public class MyController : Controller { [HttpPost(\u0026#34;/start\u0026#34;)] public IActionResult Post() { Task.Run(BackgroundOperationAsync); return Accepted(); } public async Task BackgroundOperationAsync() { var result = await CallDependencyAsync(); DoSomething(result); } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Prefer \u0026lt;code\u0026gt;Task.FromResult\u0026lt;/code\u0026gt; over \u0026lt;code\u0026gt;Task.Run\u0026lt;/code\u0026gt; for pre-computed or trivially computed data\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;For pre-computed results, there’s no need to call \u0026lt;code\u0026gt;Task.Run\u0026lt;/code\u0026gt;, that will end up queuing a work item to the thread pool that will immediately complete with the pre-computed value. Instead, use \u0026lt;code\u0026gt;Task.FromResult\u0026lt;/code\u0026gt;, to create a task wrapping already computed data.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This example wastes a thread-pool thread to return a trivially computed value.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public class MyLibrary\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;public Task AddAsync(int a, int b)\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;return Task.Run(() =\u0026amp;gt; a + b);\u0026lt;br/\u0026gt;}\u0026lt;br/\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example uses `Task.FromResult` to return the trivially computed value. It does not use any extra threads as a result. ```C# public class MyLibrary { public Task\u0026amp;amp;lt;int\u0026amp;gt; AddAsync(int a, int b) { return Task.FromResult(a + b); } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;:bulb:\u0026lt;strong\u0026gt;NOTE: Using \u0026lt;code\u0026gt;Task.FromResult\u0026lt;/code\u0026gt; will result in a \u0026lt;code\u0026gt;Task\u0026lt;/code\u0026gt; allocation. Using \u0026lt;code\u0026gt;ValueTask\u0026amp;lt;T\u0026amp;gt;\u0026lt;/code\u0026gt; can completely remove that allocation.\u0026lt;/strong\u0026gt;\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;:white_check_mark: \u0026lt;strong\u0026gt;GOOD\u0026lt;/strong\u0026gt; This example uses a \u0026lt;code\u0026gt;ValueTask\u0026amp;lt;int\u0026amp;gt;\u0026lt;/code\u0026gt; to return the trivially computed value. It does not use any extra threads as a result. It also does not allocate an object on the managed heap.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public class MyLibrary\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;public ValueTask AddAsync(int a, int b)\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;return new ValueTask(a + b);\u0026lt;br/\u0026gt;}\u0026lt;br/\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; ## Avoid using Task.Run for long running work that blocks the thread Long running work in this context refers to a thread that\u0026#39;s running for the lifetime of the application doing background work (like processing queue items, or sleeping and waking up to process some data). `Task.Run` will queue a work item to the thread pool. The assumption is that that work will finish quickly (or quickly enough to allow reusing that thread within some reasonable timeframe). Stealing a thread-pool thread for long-running work is bad since it takes that thread away from other work that could be done (timer callbacks, task continuations etc). Instead, spawn a new thread manually to do long running blocking work. :bulb: **NOTE: The thread pool grows if you block threads but it\u0026#39;s bad practice to do so.** :bulb: **NOTE:`Task.Factory.StartNew` has an option `TaskCreationOptions.LongRunning` that under the covers creates a new thread and returns a Task that represents the execution. Using this properly requires several non-obvious parameters to be passed in to get the right behavior on all platforms.** :bulb: **NOTE: Don\u0026#39;t use `TaskCreationOptions.LongRunning` with async code as this will create a new thread which will be destroyed after first `await`.** \u0026amp;amp;#x274c; **BAD** This example steals a thread-pool thread forever, to execute queued work on a `BlockingCollection\u0026amp;amp;lt;T\u0026amp;gt;`. ```C# public class QueueProcessor { private readonly BlockingCollection\u0026amp;amp;lt;Message\u0026amp;gt; _messageQueue = new BlockingCollection\u0026amp;amp;lt;Message\u0026amp;gt;(); public void StartProcessing() { Task.Run(ProcessQueue); } public void Enqueue(Message message) { _messageQueue.Add(message); } private void ProcessQueue() { foreach (var item in _messageQueue.GetConsumingEnumerable()) { ProcessItem(item); } } private void ProcessItem(Message message) { } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;:white_check_mark: \u0026lt;strong\u0026gt;GOOD\u0026lt;/strong\u0026gt; This example uses a dedicated thread to process the message queue instead of a thread-pool thread.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public class QueueProcessor\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;private readonly BlockingCollection _messageQueue = new BlockingCollection();\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; public void StartProcessing() { var thread = new Thread(ProcessQueue) { // This is important as it allows the process to exit while this thread is running IsBackground = true }; thread.Start(); } public void Enqueue(Message message) { _messageQueue.Add(message); } private void ProcessQueue() { foreach (var item in _messageQueue.GetConsumingEnumerable()) { ProcessItem(item); } } private void ProcessItem(Message message) { } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; ## Avoid using `Task.Result` and `Task.Wait` There are very few ways to use `Task.Result` and `Task.Wait` correctly so the general advice is to completely avoid using them in your code. ### :warning: Sync over `async` Using `Task.Result` or `Task.Wait` to block wait on an asynchronous operation to complete is *MUCH* worse than calling a truly synchronous API to block. This phenomenon is dubbed \u0026#34;Sync over async\u0026#34;. Here is what happens at a very high level: - An asynchronous operation is kicked off. - The calling thread is blocked waiting for that operation to complete. - When the asynchronous operation completes, it unblocks the code waiting on that operation. This takes place on another thread. The result is that we need to use 2 threads instead of 1 to complete synchronous operations. This usually leads to [thread-pool starvation](https://blogs.msdn.microsoft.com/vancem/2018/10/16/diagnosing-net-core-threadpool-starvation-with-perfview-why-my-service-is-not-saturating-all-cores-or-seems-to-stall/) and results in service outages. ### :warning: Deadlocks The `SynchronizationContext` is an abstraction that gives application models a chance to control where asynchronous continuations run. ASP.NET (non-core), WPF and Windows Forms each have an implementation that will result in a deadlock if Task.Wait or Task.Result is used on the main thread. This behavior has led to a bunch of \u0026#34;clever\u0026#34; code snippets that show the \u0026#34;right\u0026#34; way to block waiting for a Task. The truth is, there\u0026#39;s no good way to block waiting for a Task to complete. :bulb:**NOTE: ASP.NET Core does not have a `SynchronizationContext` and is not prone to the deadlock problem.** \u0026amp;amp;#x274c; **BAD** The below are all examples that are, in one way or another, trying to avoid the deadlock situation but still succumb to \u0026#34;sync over async\u0026#34; problems. ```C# public string DoOperationBlocking() { // Bad - Blocking the thread that enters. // DoAsyncOperation will be scheduled on the default task scheduler, and remove the risk of deadlocking. // In the case of an exception, this method will throw an AggregateException wrapping the original exception. return Task.Run(() =\u0026amp;gt; DoAsyncOperation()).Result; } public string DoOperationBlocking2() { // Bad - Blocking the thread that enters. // DoAsyncOperation will be scheduled on the default task scheduler, and remove the risk of deadlocking. return Task.Run(() =\u0026amp;gt; DoAsyncOperation()).GetAwaiter().GetResult(); } public string DoOperationBlocking3() { // Bad - Blocking the thread that enters, and blocking the theadpool thread inside. // In the case of an exception, this method will throw an AggregateException containing another AggregateException, containing the original exception. return Task.Run(() =\u0026amp;gt; DoAsyncOperation().Result).Result; } public string DoOperationBlocking4() { // Bad - Blocking the thread that enters, and blocking the theadpool thread inside. return Task.Run(() =\u0026amp;gt; DoAsyncOperation().GetAwaiter().GetResult()).GetAwaiter().GetResult(); } public string DoOperationBlocking5() { // Bad - Blocking the thread that enters. // Bad - No effort has been made to prevent a present SynchonizationContext from becoming deadlocked. // In the case of an exception, this method will throw an AggregateException wrapping the original exception. return DoAsyncOperation().Result; } public string DoOperationBlocking6() { // Bad - Blocking the thread that enters. // Bad - No effort has been made to prevent a present SynchonizationContext from becoming deadlocked. return DoAsyncOperation().GetAwaiter().GetResult(); } public string DoOperationBlocking7() { // Bad - Blocking the thread that enters. // Bad - No effort has been made to prevent a present SynchonizationContext from becoming deadlocked. var task = DoAsyncOperation(); task.Wait(); return task.GetAwaiter().GetResult(); } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Prefer \u0026lt;code\u0026gt;await\u0026lt;/code\u0026gt; over \u0026lt;code\u0026gt;ContinueWith\u0026lt;/code\u0026gt;\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;\u0026lt;code\u0026gt;Task\u0026lt;/code\u0026gt; existed before the async/await keywords were introduced and as such provided ways to execute continuations without relying on the language. Although these methods are still valid to use, we generally recommend that you prefer \u0026lt;code\u0026gt;async\u0026lt;/code\u0026gt;/\u0026lt;code\u0026gt;await\u0026lt;/code\u0026gt; to using \u0026lt;code\u0026gt;ContinueWith\u0026lt;/code\u0026gt;. \u0026lt;code\u0026gt;ContinueWith\u0026lt;/code\u0026gt; also does not capture the \u0026lt;code\u0026gt;SynchronizationContext\u0026lt;/code\u0026gt; and as a result is actually semantically different to \u0026lt;code\u0026gt;async\u0026lt;/code\u0026gt;/\u0026lt;code\u0026gt;await\u0026lt;/code\u0026gt;.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; The example uses \u0026lt;code\u0026gt;ContinueWith\u0026lt;/code\u0026gt; instead of \u0026lt;code\u0026gt;async\u0026lt;/code\u0026gt;\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public Task DoSomethingAsync()\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;return CallDependencyAsync().ContinueWith(task =\u0026amp;gt;\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;return task.Result + 1;\u0026lt;br/\u0026gt;});\u0026lt;br/\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example uses the `await` keyword to get the result from `CallDependencyAsync`. ```C# public async Task\u0026amp;amp;lt;int\u0026amp;gt; DoSomethingAsync() { var result = await CallDependencyAsync(); return result + 1; } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Always create \u0026lt;code\u0026gt;TaskCompletionSource\u0026amp;lt;T\u0026amp;gt;\u0026lt;/code\u0026gt; with \u0026lt;code\u0026gt;TaskCreationOptions.RunContinuationsAsynchronously\u0026lt;/code\u0026gt;\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;\u0026lt;code\u0026gt;TaskCompletionSource\u0026amp;lt;T\u0026amp;gt;\u0026lt;/code\u0026gt; is an important building block for libraries trying to adapt things that are not inherently awaitable to be awaitable via a \u0026lt;code\u0026gt;Task\u0026lt;/code\u0026gt;. It is also commonly used to build higher-level operations (such as batching and other combinators) on top of existing asynchronous APIs. By default, \u0026lt;code\u0026gt;Task\u0026lt;/code\u0026gt; continuations will run \u0026lt;em\u0026gt;inline\u0026lt;/em\u0026gt; on the same thread that calls Try/Set(Result/Exception/Canceled). As a library author, this means having to understand that calling code can resume directly on your thread. This is extremely dangerous and can result in deadlocks, thread-pool starvation, corruption of state (if code runs unexpectedly) and more.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;Always use \u0026lt;code\u0026gt;TaskCreationOptions.RunContinuationsAsynchronously\u0026lt;/code\u0026gt; when creating the \u0026lt;code\u0026gt;TaskCompletionSource\u0026amp;lt;T\u0026amp;gt;\u0026lt;/code\u0026gt;. This will dispatch the continuation onto the thread pool instead of executing it inline.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This example does not use \u0026lt;code\u0026gt;TaskCreationOptions.RunContinuationsAsynchronously\u0026lt;/code\u0026gt; when creating the \u0026lt;code\u0026gt;TaskCompletionSource\u0026amp;lt;T\u0026amp;gt;\u0026lt;/code\u0026gt;.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public Task DoSomethingAsync()\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;var tcs = new TaskCompletionSource();\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; var operation = new LegacyAsyncOperation(); operation.Completed += result =\u0026amp;gt; { // Code awaiting on this task will resume on this thread! tcs.SetResult(result); }; return tcs.Task; \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example uses `TaskCreationOptions.RunContinuationsAsynchronously` when creating the `TaskCompletionSource\u0026amp;amp;lt;T\u0026amp;gt;`. ```C# public Task\u0026amp;amp;lt;int\u0026amp;gt; DoSomethingAsync() { var tcs = new TaskCompletionSource\u0026amp;amp;lt;int\u0026amp;gt;(TaskCreationOptions.RunContinuationsAsynchronously); var operation = new LegacyAsyncOperation(); operation.Completed += result =\u0026amp;gt; { // Code awaiting on this task will resume on a different thread-pool thread tcs.SetResult(result); }; return tcs.Task; } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;:bulb:\u0026lt;strong\u0026gt;NOTE: There are 2 enums that look alike. \u0026lt;a href=\u0026#34;https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskcreationoptions?view=netcore-2.0#System_Threading_Tasks_TaskCreationOptions_RunContinuationsAsynchronously\u0026#34;\u0026gt;\u0026lt;code\u0026gt;TaskCreationOptions.RunContinuationsAsynchronously\u0026lt;/code\u0026gt;\u0026lt;/a\u0026gt; and \u0026lt;a href=\u0026#34;https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskcontinuationoptions?view=netcore-2.0\u0026#34;\u0026gt;\u0026lt;code\u0026gt;TaskContinuationOptions.RunContinuationsAsynchronously\u0026lt;/code\u0026gt;\u0026lt;/a\u0026gt;. Be careful not to confuse their usage.\u0026lt;/strong\u0026gt;\u0026lt;/p\u0026gt; \u0026lt;h2\u0026gt;Always dispose \u0026lt;code\u0026gt;CancellationTokenSource\u0026lt;/code\u0026gt;(s) used for timeouts\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;\u0026lt;code\u0026gt;CancellationTokenSource\u0026lt;/code\u0026gt; objects that are used for timeouts (are created with timers or uses the \u0026lt;code\u0026gt;CancelAfter\u0026lt;/code\u0026gt; method), can put pressure on the timer queue if not disposed.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This example does not dispose the \u0026lt;code\u0026gt;CancellationTokenSource\u0026lt;/code\u0026gt; and as a result the timer stays in the queue for 10 seconds after each request is made.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public async Task HttpClientAsyncWithCancellationBad()\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; using (var client = _httpClientFactory.CreateClient()) { var response = await client.GetAsync(\u0026#34;http://backend/api/1\u0026#34;, cts.Token); return await response.Content.ReadAsStreamAsync(); } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example disposes the `CancellationTokenSource` and properly removes the timer from the queue. ```C# public async Task\u0026amp;amp;lt;Stream\u0026amp;gt; HttpClientAsyncWithCancellationGood() { using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10))) { using (var client = _httpClientFactory.CreateClient()) { var response = await client.GetAsync(\u0026#34;http://backend/api/1\u0026#34;, cts.Token); return await response.Content.ReadAsStreamAsync(); } } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Always flow \u0026lt;code\u0026gt;CancellationToken\u0026lt;/code\u0026gt;(s) to APIs that take a \u0026lt;code\u0026gt;CancellationToken\u0026lt;/code\u0026gt;\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;Cancellation is cooperative in .NET. Everything in the call-chain has to be explicitly passed the \u0026lt;code\u0026gt;CancellationToken\u0026lt;/code\u0026gt; in order for it to work well. This means you need to explicitly pass the token into other APIs that take a token if you want cancellation to be most effective.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This example neglects to pass the \u0026lt;code\u0026gt;CancellationToken\u0026lt;/code\u0026gt; to \u0026lt;code\u0026gt;Stream.ReadAsync\u0026lt;/code\u0026gt; making the operation effectively not cancellable.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public async Task DoAsyncThing(CancellationToken cancellationToken = default)\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;byte[] buffer = new byte[1024];\u0026lt;br/\u0026gt;// We forgot to pass flow cancellationToken to ReadAsync\u0026lt;br/\u0026gt;int read = await _stream.ReadAsync(buffer, 0, buffer.Length);\u0026lt;br/\u0026gt;return Encoding.UTF8.GetString(buffer, 0, read);\u0026lt;br/\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example passes the `CancellationToken` into `Stream.ReadAsync`. ```C# public async Task\u0026amp;amp;lt;string\u0026amp;gt; DoAsyncThing(CancellationToken cancellationToken = default) { byte[] buffer = new byte[1024]; // This properly flows cancellationToken to ReadAsync int read = await _stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken); return Encoding.UTF8.GetString(buffer, 0, read); } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Cancelling uncancellable operations\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;One of the coding patterns that appears when doing asynchronous programming is cancelling an uncancellable operation. This usually means creating another task that completes when a timeout or \u0026lt;code\u0026gt;CancellationToken\u0026lt;/code\u0026gt; fires, and then using \u0026lt;code\u0026gt;Task.WhenAny\u0026lt;/code\u0026gt; to detect a complete or cancelled operation.\u0026lt;/p\u0026gt; \u0026lt;h3\u0026gt;Using CancellationTokens\u0026lt;/h3\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This example uses \u0026lt;code\u0026gt;Task.Delay(-1, token)\u0026lt;/code\u0026gt; to create a \u0026lt;code\u0026gt;Task\u0026lt;/code\u0026gt; that completes when the \u0026lt;code\u0026gt;CancellationToken\u0026lt;/code\u0026gt; fires, but if it doesn’t fire, there’s no way to dispose the \u0026lt;code\u0026gt;CancellationTokenRegistration\u0026lt;/code\u0026gt;. This can lead to a memory leak.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public static async Task WithCancellation(this Task task, CancellationToken cancellationToken)\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;// There’s no way to dispose the registration\u0026lt;br/\u0026gt;var delayTask = Task.Delay(-1, cancellationToken);\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; var resultTask = await Task.WhenAny(task, delayTask); if (resultTask == delayTask) { // Operation cancelled throw new OperationCanceledException(); } return await task; \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example disposes the `CancellationTokenRegistration` when one of the `Task(s)` complete. ```C# public static async Task\u0026amp;amp;lt;T\u0026amp;gt; WithCancellation\u0026amp;amp;lt;T\u0026amp;gt;(this Task\u0026amp;amp;lt;T\u0026amp;gt; task, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource\u0026amp;amp;lt;object\u0026amp;gt;(TaskCreationOptions.RunContinuationsAsynchronously); // This disposes the registration as soon as one of the tasks trigger using (cancellationToken.Register(state =\u0026amp;gt; { ((TaskCompletionSource\u0026amp;amp;lt;object\u0026amp;gt;)state).TrySetResult(null); }, tcs)) { var resultTask = await Task.WhenAny(task, tcs.Task); if (resultTask == tcs.Task) { // Operation cancelled throw new OperationCanceledException(cancellationToken); } return await task; } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h3\u0026gt;Using a timeout\u0026lt;/h3\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This example does not cancel the timer even if the operation successfuly completes. This means you could end up with lots of timers, which can flood the timer queue.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public static async Task TimeoutAfter(this Task task, TimeSpan timeout)\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;var delayTask = Task.Delay(timeout);\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; var resultTask = await Task.WhenAny(task, delayTask); if (resultTask == delayTask) { // Operation cancelled throw new OperationCanceledException(); } return await task; \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example cancels the timer if the operation succesfully completes. ```C# public static async Task\u0026amp;amp;lt;T\u0026amp;gt; TimeoutAfter\u0026amp;amp;lt;T\u0026amp;gt;(this Task\u0026amp;amp;lt;T\u0026amp;gt; task, TimeSpan timeout) { using (var cts = new CancellationTokenSource()) { var delayTask = Task.Delay(timeout, cts.Token); var resultTask = await Task.WhenAny(task, delayTask); if (resultTask == delayTask) { // Operation cancelled throw new OperationCanceledException(); } else { // Cancel the timer task so that it does not fire cts.Cancel(); } return await task; } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Always call \u0026lt;code\u0026gt;FlushAsync\u0026lt;/code\u0026gt; on \u0026lt;code\u0026gt;StreamWriter\u0026lt;/code\u0026gt;(s) or \u0026lt;code\u0026gt;Stream\u0026lt;/code\u0026gt;(s) before calling \u0026lt;code\u0026gt;Dispose\u0026lt;/code\u0026gt;\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;When writing to a \u0026lt;code\u0026gt;Stream\u0026lt;/code\u0026gt; or \u0026lt;code\u0026gt;StreamWriter\u0026lt;/code\u0026gt;, even if the asynchronous overloads are used for writing, the underlying data might be buffered. When data is buffered, disposing the \u0026lt;code\u0026gt;Stream\u0026lt;/code\u0026gt; or \u0026lt;code\u0026gt;StreamWriter\u0026lt;/code\u0026gt; via the \u0026lt;code\u0026gt;Dispose\u0026lt;/code\u0026gt; method will synchronously write/flush, which results in blocking the thread and could lead to thread-pool starvation. Either use the asynchronous \u0026lt;code\u0026gt;DisposeAsync\u0026lt;/code\u0026gt; method (for example via \u0026lt;code\u0026gt;await using\u0026lt;/code\u0026gt;) or call \u0026lt;code\u0026gt;FlushAsync\u0026lt;/code\u0026gt; before calling \u0026lt;code\u0026gt;Dispose\u0026lt;/code\u0026gt;.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;:bulb:\u0026lt;strong\u0026gt;NOTE: This is only problematic if the underlying subsystem does IO.\u0026lt;/strong\u0026gt;\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This example ends up blocking the request by writing synchronously to the HTTP-response body.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;app.Run(async context =\u0026amp;gt;\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;// The implicit Dispose call will synchronously write to the response body\u0026lt;br/\u0026gt;using (var streamWriter = new StreamWriter(context.Response.Body))\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;await streamWriter.WriteAsync(“Hello World”);\u0026lt;br/\u0026gt;}\u0026lt;br/\u0026gt;});\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example asynchronously flushes any buffered data while disposing the `StreamWriter`. ```C# app.Run(async context =\u0026amp;gt; { // The implicit AsyncDispose call will flush asynchronously await using (var streamWriter = new StreamWriter(context.Response.Body)) { await streamWriter.WriteAsync(\u0026#34;Hello World\u0026#34;); } }); \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;:white_check_mark: \u0026lt;strong\u0026gt;GOOD\u0026lt;/strong\u0026gt; This example asynchronously flushes any buffered data before disposing the \u0026lt;code\u0026gt;StreamWriter\u0026lt;/code\u0026gt;.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;app.Run(async context =\u0026amp;gt;\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;using (var streamWriter = new StreamWriter(context.Response.Body))\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;await streamWriter.WriteAsync(“Hello World”);\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; // Force an asynchronous flush await streamWriter.FlushAsync(); } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;});\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; ## Prefer `async`/`await` over directly returning `Task` There are benefits to using the `async`/`await` keyword instead of directly returning the `Task`: - Asynchronous and synchronous exceptions are normalized to always be asynchronous. - The code is easier to modify (consider adding a `using`, for example). - Diagnostics of asynchronous methods are easier (debugging hangs etc). - Exceptions thrown will be automatically wrapped in the returned `Task` instead of surprising the caller with an actual exception. \u0026amp;amp;#x274c; **BAD** This example directly returns the `Task` to the caller. ```C# public Task\u0026amp;amp;lt;int\u0026amp;gt; DoSomethingAsync() { return CallDependencyAsync(); } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;:white_check_mark: \u0026lt;strong\u0026gt;GOOD\u0026lt;/strong\u0026gt; This examples uses async/await instead of directly returning the Task.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public async Task DoSomethingAsync()\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;return await CallDependencyAsync();\u0026lt;br/\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :bulb:**NOTE: There are performance considerations when using an async state machine over directly returning the `Task`. It\u0026#39;s always faster to directly return the `Task` since it does less work but you end up changing the behavior and potentially losing some of the benefits of the async state machine.** ## ConfigureAwait TBD # Scenarios The above tries to distill general guidance, but doesn\u0026#39;t do justice to the kinds of real-world situations that cause code like this to be written in the first place (bad code). This section tries to take concrete examples from real applications and turn them into something simple to help you relate these problems to existing codebases. ## `Timer` callbacks \u0026amp;amp;#x274c; **BAD** The `Timer` callback is `void`-returning and we have asynchronous work to execute. This example uses `async void` to accomplish it and as a result can crash the process if an exception occurs. ```C# public class Pinger { private readonly Timer _timer; private readonly HttpClient _client; public Pinger(HttpClient client) { _client = client; _timer = new Timer(Heartbeat, null, 1000, 1000); } public async void Heartbeat(object state) { await _client.GetAsync(\u0026#34;http://mybackend/api/ping\u0026#34;); } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This attempts to block in the \u0026lt;code\u0026gt;Timer\u0026lt;/code\u0026gt; callback. This may result in thread-pool starvation and is an example of \u0026lt;a href=\u0026#34;/index.html%3Fp=1415.html#warning-sync-over-async\u0026#34;\u0026gt;sync over async\u0026lt;/a\u0026gt;\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public class Pinger\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;private readonly Timer _timer;\u0026lt;br/\u0026gt;private readonly HttpClient _client;\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; public Pinger(HttpClient client) { _client = client; _timer = new Timer(Heartbeat, null, 1000, 1000); } public void Heartbeat(object state) { _client.GetAsync(\u0026#34;http://mybackend/api/ping\u0026#34;).GetAwaiter().GetResult(); } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example uses an `async Task`-based method and discards the `Task` in the `Timer` callback. If this method fails, it will not crash the process. Instead, it will fire the [`TaskScheduler.UnobservedTaskException`](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskscheduler.unobservedtaskexception?view=netframework-4.7.2) event. ```C# public class Pinger { private readonly Timer _timer; private readonly HttpClient _client; public Pinger(HttpClient client) { _client = client; _timer = new Timer(Heartbeat, null, 1000, 1000); } public void Heartbeat(object state) { // Discard the result _ = DoAsyncPing(); } private async Task DoAsyncPing() { await _client.GetAsync(\u0026#34;http://mybackend/api/ping\u0026#34;); } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Implicit \u0026lt;code\u0026gt;async void\u0026lt;/code\u0026gt; delegates\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;Imagine a \u0026lt;code\u0026gt;BackgroundQueue\u0026lt;/code\u0026gt; with a \u0026lt;code\u0026gt;FireAndForget\u0026lt;/code\u0026gt; that takes a callback. This method will execute the callback at some time in the future.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This will force callers to either block in the callback or use an \u0026lt;code\u0026gt;async void\u0026lt;/code\u0026gt; delegate.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public class BackgroundQueue\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;public static void FireAndForget(Action action) { }\u0026lt;br/\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; \u0026amp;amp;#x274c; **BAD** This calling code is creating an `async void` method implicitly. The compiler fully supports this today. ```C# public class Program { public void Main(string[] args) { var httpClient = new HttpClient(); BackgroundQueue.FireAndForget(async () =\u0026amp;gt; { await httpClient.GetAsync(\u0026#34;http://pinger/api/1\u0026#34;); }); Console.ReadLine(); } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;:white_check_mark: \u0026lt;strong\u0026gt;GOOD\u0026lt;/strong\u0026gt; This BackgroundQueue implementation offers both sync and \u0026lt;code\u0026gt;async\u0026lt;/code\u0026gt; callback overloads.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public class BackgroundQueue\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;public static void FireAndForget(Action action) { }\u0026lt;br/\u0026gt;public static void FireAndForget(Func action) { }\u0026lt;br/\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; ## `ConcurrentDictionary.GetOrAdd` It\u0026#39;s pretty common to cache the result of an asynchronous operation and `ConcurrentDictionary` is a good data structure for doing that. `GetOrAdd` is a convenience API for trying to get an item if it\u0026#39;s already there or adding it if it isn\u0026#39;t. The callback is synchronous so it\u0026#39;s tempting to write code that uses `Task.Result` to produce the value of an asynchronous process but that can lead to thread-pool starvation. \u0026amp;amp;#x274c; **BAD** This may result in thread-pool starvation since we\u0026#39;re blocking the request thread if the person data is not cached. ```C# public class PersonController : Controller { private AppDbContext _db; // This cache needs expiration private static ConcurrentDictionary\u0026amp;amp;lt;int, Person\u0026amp;gt; _cache = new ConcurrentDictionary\u0026amp;amp;lt;int, Person\u0026amp;gt;(); public PersonController(AppDbContext db) { _db = db; } public IActionResult Get(int id) { var person = _cache.GetOrAdd(id, (key) =\u0026amp;gt; _db.People.FindAsync(key).Result); return Ok(person); } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;:white_check_mark: \u0026lt;strong\u0026gt;GOOD\u0026lt;/strong\u0026gt; This implementation won’t result in thread-pool starvation since we’re storing a task instead of the result itself.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;:warning: \u0026lt;code\u0026gt;ConcurrentDictionary.GetOrAdd\u0026lt;/code\u0026gt; will potentially run the cache callback multiple times in parallel. This can result in kicking off expensive computations multiple times.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public class PersonController : Controller\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;private AppDbContext _db;\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;// This cache needs expiration\u0026lt;br/\u0026gt;private static ConcurrentDictionary\u0026amp;lt;int, Task\u0026amp;gt; _cache = new ConcurrentDictionary\u0026amp;lt;int, Task\u0026amp;gt;();\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;public PersonController(AppDbContext db)\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;_db = db;\u0026lt;br/\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;public async Task Get(int id)\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;var person = await _cache.GetOrAdd(id, (key) =\u0026amp;gt; _db.People.FindAsync(key));\u0026lt;br/\u0026gt;return Ok(person);\u0026lt;br/\u0026gt;}\u0026lt;br/\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This implementation fixes the multiple-executing callback issue by using the `async` lazy pattern. ```C# public class PersonController : Controller { private AppDbContext _db; // This cache needs expiration private static ConcurrentDictionary\u0026amp;amp;lt;int, AsyncLazy\u0026amp;amp;lt;Person\u0026amp;gt;\u0026amp;gt; _cache = new ConcurrentDictionary\u0026amp;amp;lt;int, AsyncLazy\u0026amp;amp;lt;Person\u0026amp;gt;\u0026amp;gt;(); public PersonController(AppDbContext db) { _db = db; } public async Task\u0026amp;amp;lt;IActionResult\u0026amp;gt; Get(int id) { var person = await _cache.GetOrAdd(id, (key) =\u0026amp;gt; new AsyncLazy\u0026amp;amp;lt;Person\u0026amp;gt;(() =\u0026amp;gt; _db.People.FindAsync(key))).Value; return Ok(person); } private class AsyncLazy\u0026amp;amp;lt;T\u0026amp;gt; : Lazy\u0026amp;amp;lt;Task\u0026amp;amp;lt;T\u0026amp;gt;\u0026amp;gt; { public AsyncLazy(Func\u0026amp;amp;lt;Task\u0026amp;amp;lt;T\u0026amp;gt;\u0026amp;gt; valueFactory) : base(valueFactory) { } } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;h2\u0026gt;Constructors\u0026lt;/h2\u0026gt; \u0026lt;p\u0026gt;Constructors are synchronous. If you need to initialize some logic that may be asynchronous, there are a couple of patterns for dealing with this.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;Here’s an example of using a client API that needs to connect asynchronously before use.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public interface IRemoteConnectionFactory\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;Task ConnectAsync();\u0026lt;br/\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;public interface IRemoteConnection\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;Task PublishAsync(string channel, string message);\u0026lt;br/\u0026gt;Task DisposeAsync();\u0026lt;br/\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; \u0026amp;amp;#x274c; **BAD** This example uses `Task.Result` to get the connection in the constructor. This could lead to thread-pool starvation and deadlocks. ```C# public class Service : IService { private readonly IRemoteConnection _connection; public Service(IRemoteConnectionFactory connectionFactory) { _connection = connectionFactory.ConnectAsync().Result; } } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;:white_check_mark: \u0026lt;strong\u0026gt;GOOD\u0026lt;/strong\u0026gt; This implementation uses a static factory pattern in order to allow asynchronous construction:\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public class Service : IService\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;private readonly IRemoteConnection _connection;\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; private Service(IRemoteConnection connection) { _connection = connection; } public static async Task\u0026amp;amp;lt;Service\u0026amp;gt; CreateAsync(IRemoteConnectionFactory connectionFactory) { return new Service(await connectionFactory.ConnectAsync()); } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; ## WindowsIdentity.RunImpersonated This API runs the specified action as the impersonated Windows identity. Unfortunately there\u0026#39;s no asynchronous version of the callback. \u0026amp;amp;#x274c; **BAD** This example tries to execute the query asynchronously, and then wait for it outside of the call to `RunImpersonated`. This will throw because the query might be executing outside of the impersonation context. ```C# public async Task\u0026amp;amp;lt;IEnumerable\u0026amp;amp;lt;Product\u0026amp;gt;\u0026amp;gt; GetDataImpersonatedAsync(SafeAccessTokenHandle safeAccessTokenHandle) { Task\u0026amp;amp;lt;IEnumerable\u0026amp;amp;lt;Product\u0026amp;gt;\u0026amp;gt; products = null; WindowsIdentity.RunImpersonated( safeAccessTokenHandle, context =\u0026amp;gt; { products = _db.QueryAsync(\u0026#34;SELECT Name from Products\u0026#34;); }}; return await products; } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; \u0026lt;p\u0026gt;❌ \u0026lt;strong\u0026gt;BAD\u0026lt;/strong\u0026gt; This example uses \u0026lt;code\u0026gt;Task.Result\u0026lt;/code\u0026gt; to get the connection in the constructor. This could lead to thread-pool starvation and deadlocks.\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;“`C#\u0026lt;br/\u0026gt;public IEnumerable GetDataImpersonatedAsync(SafeAccessTokenHandle safeAccessTokenHandle)\u0026lt;br/\u0026gt;{\u0026lt;br/\u0026gt;return WindowsIdentity.RunImpersonated(\u0026lt;br/\u0026gt;safeAccessTokenHandle,\u0026lt;br/\u0026gt;context =\u0026amp;gt; _db.QueryAsync(“SELECT Name from Products”).Result);\u0026lt;br/\u0026gt;}\u0026lt;/p\u0026gt; \u0026lt;div\u0026gt;\u0026lt;pre class=\u0026#34;brush: plain; title: ; notranslate\u0026#34; title=\u0026#34;\u0026#34;\u0026gt; :white_check_mark: **GOOD** This example awaits the result of `RunImpersonated` (the delegate is `Func\u0026amp;amp;lt;Task\u0026amp;amp;lt;IEnumerable\u0026amp;amp;lt;Product\u0026amp;gt;\u0026amp;gt;\u0026amp;gt;` in this case). ```C# public async Task\u0026amp;amp;lt;IEnumerable\u0026amp;amp;lt;Product\u0026amp;gt;\u0026amp;gt; GetDataImpersonatedAsync(SafeAccessTokenHandle safeAccessTokenHandle) { return await WindowsIdentity.RunImpersonated( safeAccessTokenHandle, context =\u0026amp;gt; _db.QueryAsync(\u0026#34;SELECT Name from Products\u0026#34;)); } \u0026lt;/pre\u0026gt;\u0026lt;/div\u0026gt; ","date":"30 June 2020","externalUrl":null,"permalink":"/asynchronous-programming-the-right-way/","section":"Articles","summary":"There is a right way and a wrong way with programme Asynchronously, mainly due to the initial way Microsoft brought in Async programming was not best practise and they have now made changes to make it more effective and be more productive.\n","title":"Asynchronous Programming the right way","type":"articles"},{"content":"Overview JSON Web Tokens is an emerging standard. They are very close to their standardisation. IETF has taken care of that, and OpenID connect mandates the use of JSON Web token for all of the tokens that are exchanged in that protocol. this article gives you a little look, an overview of the purpose of security tokens, and, and what other types of tokens we have out there and where, where they are used. Then we have a look at the structure of a JSON Web Token, and then we’ll show you how easy it is to create and consume them using the Microsoft DotNet Core development framework.\nThe Purpose of Security Tokens The purpose of a security token is really to produce a data structure that contains information about the issuer and about maybe the recipient and about the subject that this token describes. Think of an authentication operation where you sign in somewhere, and the authentication server sends back to the application a token that defines your identity, holding all the information about you and your session. Obviously must be protected so nobody can tamper with that and change its contents. So these tokens are also signed. Depending on the technology, you either sign them symmetrically or asymmetrically and signing moreover fulfils the need or the purpose of making them authentic, meaning the recipient of that token wants to make sure it is coming from a trusted source. When you trust the issuer of the token, you can also trust the contents of the token, and the claims which are typically inside of the token. Tokens usually contain an expiration time, so you know, they only have a limited validity Depending on the scenario, this might be something like a workday. Or maybe with access tokens, they are very short-lived, like an hour or even shorter. So tokens are very important, they are critical aspects to all of the protocols in the security space. Thus, a client which is an application, requests the token, an issuer issues a token and a resource consumes a token. JWT Structure and Format JWT is on its way to official standardisation\nhttps://tools.ietf.org/html/draft-ietf-oauth-access-token-jwt-07 So how does the JSON Web Token look like? It basically has two parts one is the header which provides some metadata and some information about which algorithms and which keys are used for, for doing the cryptographic operations, and it has a number of it has claims just generally speaking.\nHeader\nmetadata algorithms \u0026amp; keys used Claims\nIssuer(iss) Audience(aud) IssuedAt(iat) Expriation(exp) Subject(sub) ..and application defended claims There are claims fall into two areas one is reserved claims. Some of them you see here on the slide, and then you can have application-defined claims that you can freely define. Essential a token has at least an issuer claim, so the recipient knows where the token is coming from. It has an audience claim, so the recipient knows that he is the right recipient for the token and not someone else.\nHere they typically have an IssuedAt claim, which tells the recipient when the token was issued, an Expiration claim relating the recipient when the token has expired, and the Subject claim, which is basically like an identifier of the entity that this token describes, like a UserID for example.\nHeader { \"alg\": \"HS256\", \"typ\": \"JWT\" } Claims { \u0026ldquo;iss\u0026rdquo;: \u0026ldquo;abc\u0026rdquo;, \u0026ldquo;unique_name\u0026rdquo;: \u0026ldquo;2\u0026rdquo;, \u0026ldquo;nbf\u0026rdquo;: 1590849115, \u0026ldquo;exp\u0026rdquo;: 1590849175, \u0026ldquo;iat\u0026rdquo;: 1590849115,\n\u0026ldquo;client\u0026rdquo;: \u0026ldquo;acme\u0026rdquo;, \u0026ldquo;scope\u0026rdquo;: [\u0026ldquo;read\u0026rdquo;, \u0026ldquo;search\u0026rdquo;] } The structure of a sample JSON Web Token. You can see on top we have the header section. The algorithm says here that we are using an HMAC SHA-256 to assign the token. Now in the claims section, you see some of the claims. The expiration is an epoch time. Meaning you’re taking the number of seconds from the first January of 1970. So that’s the way they get around all the different date-time encodings on cross-platform. Producing and Consuming JWTs So how would you produce a token? A very good and simple working example of JWT in action is produced by Jason Watmore:\nhttps://github.com/cornflourblue/aspnet-core-3-jwt-authentication-api\nA Microsoft library on NuGet that implements JSON Web Token handling. It has a classes called JSON Web Token, SecurityToken, or JWTSecurityToken. And you pass in the claims that we talked about earlier, so like the Issuer claim, the Audience claims that describe the subject. var token = new JWTSecurityToken( issuer: \"http://myIssuer\", audience: \"http://myResource\", claims: GetClaims(), signingCredentials: GetKey(), validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.AddHours(1)); // serialize var tokenString = new JWTSecurityTokenHandler().WriteToken(token);\nYou tell the class what’s the signing credential, and you tell them that the validFrom, validTo thing. And then you can use a class called the JWTSecurityTokenHandler to serialise the token. Then you can just transmit that via arbitrary means. You could put on a header in an HTTP request, you could put it in the query string , you could even put it into a cookie. It doesn’t matter it’s just a string, that you can pass around in your system in a very flexible way. Now the consumer of that token, the most common thing obviously, would be in the HTTP header. To validate a token, you just read that string, you put it back into this short security token class. You set some validation parameters, for example\nvar token = new JWTSecurityToken(tokenString); var validationParams = new TokenValidationParameters { ValidIssuer = \"http://myIssuer\", AllowedAudience = \"http://myResource\", SigningToken = GetSigningKey() }; var handler = new JWTSecurityTokenHandler(); var principal = handler.ValidateToken(token, validationParams);\nThe issuer to be my issuer, your audience to be myResource, and that is the signing key that you use to validate the signature. It’s that easy, there are libraries for all platforms like Java and PHP and, and Node and so on, that can deal with JSON Web Tokens.\n","date":"30 May 2020","externalUrl":null,"permalink":"/json-web-tokens-jwt/","section":"Articles","summary":"Overview JSON Web Tokens is an emerging standard. They are very close to their standardisation. IETF has taken care of that, and OpenID connect mandates the use of JSON Web token for all of the tokens that are exchanged in that protocol. this article gives you a little look, an overview of the purpose of security tokens, and, and what other types of tokens we have out there and where, where they are used. Then we have a look at the structure of a JSON Web Token, and then we’ll show you how easy it is to create and consume them using the Microsoft DotNet Core development framework.\n","title":"JSON Web Tokens (JWT)","type":"articles"},{"content":"Here is a simple REST Client talking to a stand along Server API all written in DotNet Core 3.1.\nIt is loosely based on creating a simple REST Client, an tutorial from Microsoft can give you the very basic features in DotNet Core\nhttps://docs.microsoft.com/en-us/dotnet/csharp/tutorials/console-webapiclient\nI created a simple Server API with one end point to return a password with the version number and which machine it was generated on.\nInitial Source can be found here under this tag:\nhttps://github.com/BryanAvery/REST-Client-Server-API/releases/tag/BasicClientServerAPI\nDocker Next stage is to containerise both applications\nTo build the ServerApi:\ndocker build -t password-api -f Docker/ServerApi/Dockerfile . To run the ServerApi:\ndocker run -p 5001:5001 password-api Like wise with the Web Api Client just replace the name with web-api-client\ndocker-compose Next I’ve generated the docker-compose.yml file to allow for a single build to the environment.\nIt is as simple as running the single line to build everything for you\ndocker-compose -f Docker/docker-compose.yml up -d --build ","date":"25 May 2020","externalUrl":null,"permalink":"/rest-client-server-api/","section":"Articles","summary":"Here is a simple REST Client talking to a stand along Server API all written in DotNet Core 3.1.\nIt is loosely based on creating a simple REST Client, an tutorial from Microsoft can give you the very basic features in DotNet Core\nhttps://docs.microsoft.com/en-us/dotnet/csharp/tutorials/console-webapiclient\n","title":"REST Client / Server API","type":"articles"},{"content":"Nice video to attached a BitBucket Server to Jenkins\n","date":"28 April 2020","externalUrl":null,"permalink":"/bitbucket-server-to-jenkins/","section":"Articles","summary":"Nice video to attached a BitBucket Server to Jenkins\n","title":"BitBucket Server to Jenkins","type":"articles"},{"content":"","date":"28 April 2020","externalUrl":null,"permalink":"/categories/jenkins/","section":"Categories","summary":"","title":"Jenkins","type":"categories"},{"content":"Using DotNet Core comes some responsibilities, one of those is making sure your application is up and running.\nSince DotNet Core 2.2 the introductions of health checks have been established.\nThere are two types of Health Checks\nLiveness Health Checks Readiness Health Checks Liveness Health Check has the ability to report that your application is running\nReadiness Health Check which can check any additional functionality that your application needs to function.\nAll the health checks provide an Endpoint which provides a Health Response which can be either Healthy, Degraded or Unhealthy\nYou can have multiple Health Checks which can be monitored from different systems such as:\nMonitoring System Load Balancer Container Orchestrators Deployment Tool And depending on the Health Status each system can react and deal with the results accordingly.\nI have created a sample application that formats the Health results and displays a UI for the results.\nThe example connects to:\na database external API file in your file system I’ve also included two examples of Health Check extensions to show how to create a custom HealthCheck\nTaking the application further you can use the following:\nRate Limit Authorization Authentication Limited the rate of calls to the Health Check endpoints, we can do this using AspNetCoreRateLimit is an ASP.NET Core rate limiting solution designed to control the rate of requests that clients can make to a Web API or MVC app based on IP address or client ID.\nIn the AppSettings you set the IpRateLimiting section for the limiter\nFor Authorization you just need to add to the end of the EndPoint:\n.RequireAuthorization()\nFor Authentication you just need to add to the end of the EndPoint:\n.RequireAuthorization(\"HealthCheckPolicy\") Hope this helps you understand and build better Health Checks within your DotNet Core application.\nThe source can be found here:\nhttps://github.com/BryanAvery/HealthChecks\n","date":"19 April 2020","externalUrl":null,"permalink":"/health-checks/","section":"Articles","summary":"Using DotNet Core comes some responsibilities, one of those is making sure your application is up and running.\nSince DotNet Core 2.2 the introductions of health checks have been established.\nThere are two types of Health Checks\n","title":"Health Checks","type":"articles"},{"content":"","date":"14 April 2020","externalUrl":null,"permalink":"/categories/docker/","section":"Categories","summary":"","title":"Docker","type":"categories"},{"content":"Recently I was playing with docker API on OSX to use with Jenkins and the setup was little complicated so I thought to put all steps together in one place. Just to summarise the default tcp port for docker is 2375 (unencrypted) and 2376(encrypted) communication over tcp(although we can choose any other port).\nThe setup on linux is fairly straight away using systemd and a lot of help is out there however on OSX there are issues to deal with.\nFor security reasons , on OSX the default tcp port is not exposed and listens to socket/var/run/docker.sock .\nThe way I got it working was to consume docker api on your OSX. Easy way: Use socat container . This container can redirect the Docker API exposed on the unix domain socket in Linux to the port of our choice on OSX host. Most of the time you will need this if you want to just play with api. On your shell run – \u0026gt;\u0026gt; docker run -d -v /var/run/docker.sock:/var/run/docker.sock --name socat -p 127.0.0.1:2375:2375 bobrik/socat TCP-LISTEN:2375,fork UNIX-CONNECT:/var/run/docker.sock \u0026gt;\u0026gt; export DOCKER_HOST=tcp://localhost:2375 \u0026gt;\u0026gt; curl localhost:2375/images/json | jq . ","date":"14 April 2020","externalUrl":null,"permalink":"/enabling-docker-remote-api-on-osx/","section":"Articles","summary":"Recently I was playing with docker API on OSX to use with Jenkins and the setup was little complicated so I thought to put all steps together in one place. Just to summarise the default tcp port for docker is 2375 (unencrypted) and 2376(encrypted) communication over tcp(although we can choose any other port).\n","title":"Enabling docker remote API on OSX","type":"articles"},{"content":"Docker_Image_Security_Best_Practices_Download Original files from: snyk\n","date":"13 April 2020","externalUrl":null,"permalink":"/10-docker-image-security-best-practices/","section":"Articles","summary":"Docker_Image_Security_Best_Practices_Download Original files from: snyk\n","title":"10 Docker image security best practices","type":"articles"},{"content":"Quick and easy way to setup an SMTP mail server using docker\ndocker run --restart unless-stopped --name mailhog -p 1025:1025 -p 8025:8025 -d mailhog/mailhog ","date":"13 April 2020","externalUrl":null,"permalink":"/local-smtp-server-on-docker/","section":"Articles","summary":"Quick and easy way to setup an SMTP mail server using docker\ndocker run --restart unless-stopped --name mailhog -p 1025:1025 -p 8025:8025 -d mailhog/mailhog ","title":"Local Smtp server on Docker","type":"articles"},{"content":"We love Jenkins and we love Docker, so let’s get them working together.\nWe are assuming you already have Docker installed on your environment.\nHere is the terminal command to use:\ndocker run -p 8080:8080 -p 50000:50000 -v /Jenkins/jenkins-master:/var/jenkins_home --name jenkins-master jenkins/jenkins:lts Let’s break it down:\n-p 8080:8080 Run Jenkins on the default port 8080 in the hosted environment -p 50000:50000 Again this is for Jenkins to be exposed to the host environment -v {host location}:/var/jenkins_home Persist the data to your local volume –name jenkins-master give the Docker an image name that we can understand jenkins/jenkins:lts use the latest stable build version Just make sure you have the {host location} in the docker Resource/File Sharing in order for the image to be able to see that location.\nIt is really that simple, just remember the initial password will be held in the following folder on your Docker Image:\n/var/jenkins_home/secrets/initialAdminPassword\n","date":"12 April 2020","externalUrl":null,"permalink":"/jenkins-in-docker/","section":"Articles","summary":"We love Jenkins and we love Docker, so let’s get them working together.\nWe are assuming you already have Docker installed on your environment.\nHere is the terminal command to use:\ndocker run -p 8080:8080 -p 50000:50000 -v /Jenkins/jenkins-master:/var/jenkins_home --name jenkins-master jenkins/jenkins:lts Let’s break it down:\n","title":"Jenkins in Docker","type":"articles"},{"content":"Many of today’s website is designed around giving a good user experience. This comes at a cost of high-bandwidth. Not everyone in the world will have a good internet connection, how about when you are at sea on a ship or in a developing country such as India or Pakistan.\nSo what can be done to provide a solution for these low-bandwidth situations? There is no one solution as when architecting a solution it is delicate between features richness, performance and time to market.\nArchitecture How can the architecture help with low-bandwidth\nProgressive Enhancement and PWAs (Progressive Web Applications) These are Connectivity independent, safe and installable applications Universal Javascript is the future Adaptive Web Development This uses static layouts based on breakpoints which don’t respond once they’re initially loaded. Not ideal, but if push comes to shove and you need your app to work on a feature phone, you might need to serve out a different page altogether Server-Side Rendering when possible Sometimes, you don’t need Single Page Applications. A simple server-rendered static website would do. Static sites work across browsers, network conditions, geographies and require little to no Javascript. If you can make do with one, then your work is cut out for you. Development Develop mobile-first – it always helps with perf Best Practices – Trim, Bundle, GZIP and Tree Shake your code to make it lean. Testing Testing should be done on\nReal devices Real networks Monitoring Performance should be constantly monitored, and performance bugs should be seen as at par with others. Performance Sprints between regular development cycles ","date":"26 February 2020","externalUrl":null,"permalink":"/low-bandwidth-website/","section":"Articles","summary":"Many of today’s website is designed around giving a good user experience. This comes at a cost of high-bandwidth. Not everyone in the world will have a good internet connection, how about when you are at sea on a ship or in a developing country such as India or Pakistan.\n","title":"Low-Bandwidth website","type":"articles"},{"content":"Here is a working example of a simple Docker file for a .NET Core 3.1 project\nFROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env WORKDIR /app COPY project.csproj ./ RUN dotnet restore\nCOPY . ./ RUN dotnet publish -c Release -o out\nFROM mcr.microsoft.com/dotnet/core/runtime:3.1\nWORKDIR /app COPY \u0026ndash;from=build-env /app/out .\nENTRYPOINT [\u0026ldquo;dotnet\u0026rdquo;, \u0026ldquo;project.dll\u0026rdquo;]\n","date":"20 February 2020","externalUrl":null,"permalink":"/sample-net-core-docker-file/","section":"Articles","summary":"Here is a working example of a simple Docker file for a .NET Core 3.1 project\nFROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env WORKDIR /app COPY project.csproj ./ RUN dotnet restore\nCOPY . ./ RUN dotnet publish -c Release -o out\nFROM mcr.microsoft.com/dotnet/core/runtime:3.1\nWORKDIR /app COPY –from=build-env /app/out .\nENTRYPOINT [“dotnet”, “project.dll”]","title":"Sample .NET Core Docker file","type":"articles"},{"content":"Build Build an image from the Dockerfile in the current directory and tag the image\ndocker build -t myimage -f Dockerfile . List all images that are locally stored with the Docker Engine\ndocker ps -a Delete an image from the local image store\ndocker image rm CONTAINER_NAME You may want to remove all orphaned images, you can do this with dandling field\ndocker rmi $(docker images -f dangling=true -q) Run Run a container from the myimage\ndocker run -it --rm myimage Stop a running container\ndocker stop myimage Kill a running container\ndocker container kill web List the running containers (add –all to include stopped containers)\ndocker container ls Delete all running and stopped container\ndocker container rm -f $(docker ps -aq) Print the last 100 lines of a container’s logs\ndocker container logs --tail 100 web Containers Your basic isolated Docker process. Containers are to Virtual Machines as threads are to processes. Or you can think of them as chroots on steroids.\nLifecycle docker create creates a container but does not start it. docker rename allows the container to be renamed. docker run creates and starts a container in one operation. docker rm deletes a container. docker update updates a container’s resource limits. Normally if you run a container without options it will start and stop immediately, if you won’t keep it running you can use the command, docker run -td container_id this will use the option -t that will allocate a pseudo-TTY session and -d that will detach automatically the container (run container in background and print container ID).\nIf you want a transient container, docker run --rm will remove the container after it stops.\nIf you want to map a directory on the host to a docker container, docker run -v $HOSTDIR:$DOCKERDIR. Also, see Volumes.\nIf you want to remove also the volumes associated with the container, the deletion of the container must include the -v switch like in docker rm -v.\nThere’s also a logging driver available for individual containers in docker 1.10. To run docker with a custom log driver (i.e., to syslog), use docker run --log-driver=syslog.\nAnother useful option is docker run --name yourname docker_image because when you specify the --name inside the run command, this will allow you to start and stop a container by calling it with the name you specified when you created it.\nStarting and Stopping docker start starts a container so it is running. docker stop stops a running container. docker restart stops and starts a container. docker pause pauses a running container, “freezing” it in place. docker unpause will unpause a running container. docker wait blocks until running container stops. docker kill sends a SIGKILL to a running container. docker attach will connect to a running container. If you want to detach from a running container, use Ctrl + p, Ctrl + q. If you want to integrate a container with a host process manager, start the daemon with -r=false then use docker start -a.\nIf you want to expose container ports through the host, see the exposing ports section.\nSimple working example can be found here:\nhttps://docs.microsoft.com/en-us/dotnet/core/docker/build-container\nDocker Cheat Sheet\nhttps://github.com/wsargent/docker-cheat-sheet\n","date":"17 February 2020","externalUrl":null,"permalink":"/docker-cribsheet/","section":"Articles","summary":"Build Build an image from the Dockerfile in the current directory and tag the image\ndocker build -t myimage -f Dockerfile . List all images that are locally stored with the Docker Engine\ndocker ps -a Delete an image from the local image store\n","title":"Docker cribsheet","type":"articles"},{"content":"What Are Containers? Containers are a form of operating system virtualization. A single container might be used to run anything from a small microservice or software process to a larger application. Inside a container are all the necessary executables, binary code, libraries, and configuration files. Compared to server or machine virtualization approaches, however, containers do not contain operating system images. This makes them more lightweight and portable, with significantly less overhead. In larger application deployments, multiple containers may be deployed as one or more container clusters. Such clusters might be managed by a container orchestrator such as Kubernetes.\nBenefits of Containers Containers are a streamlined way to build, test, deploy, and redeploy applications on multiple environments from a developer’s local laptop to an on-premises data centre and even the cloud. Benefits of containers include:\nLess overhead. Containers require fewer system resources than traditional or hardware virtual machine environments because they don’t include operating system images. Increased portability. Applications running in containers can be deployed easily to multiple different operating systems and hardware platforms. More consistent operation. DevOps teams know applications in containers will run the same, regardless of where they are deployed. Greater efficiency. Containers allow applications to be more rapidly deployed, patched, or scaled. Better application development. Containers support agile and DevOps efforts to accelerate development, test, and production cycles. Container Use Cases Common ways organizations use containers include:\n“Lift and shift” existing applications into modern cloud architectures. Some organizations use containers to migrate existing applications into more modern environments. While this practice delivers some of the basic benefits of operating system virtualization, it does not offer the full benefits of modular, container-based application architecture. Refactor existing applications for containers. Although refactoring is much more intensive than lift-and-shift migration, it enables the full benefits of a container environment. Develop new container-native applications. Much like refactoring, this approach unlocks the full benefits of containers. Provide better support for microservices architectures. Distributed applications and microservices can be more easily isolated, deployed, and scaled using individual container building blocks. Provide DevOps support for continuous integration and deployment (CI/CD). Container technology supports streamlined build, test, and deployment from the same container images. Provide easier deployment of repetitive jobs and tasks. Containers are being deployed to support one or more similar processes, which often run in the background, such as ETL functions or batch jobs. Original article: What Are Containers?\nDisadvantages and Challenges After praising Container, let’s consider the drawbacks and challenges when using Containers:\nIncreased complexity due to an additional layer. This affects not only the deployment but also the development and build. In addition, managing a huge amount of containers is challenging – especially when it comes to clustering containers. Tools like Google Kubernetes and Apache Mesos can help here. The containers share the same kernel and are therefore less isolated than real VMs. A bug in the kernel affects every container. Container bases on Linux Containers (LXC), which is a Linux technology. Therefore, we can’t run Containers on other systems and our container is always a Linux system. But Boot2Docker enables the usage of Container on Windows and Mac OS X by using VirtualBox. The Container client runs on the host OS and communicates with the Container daemon inside the VirtualBox. Unfortunately, this is less comfortable and makes daily use clumsy and more complicated than running Containers natively. Introducing Containers can be a demanding and time-consuming task. We have to evaluate if it is worth the effort and the increased complexity. The management rejected Containers with the argument, that 3 nodes (production, pre-production and experimental) are not enough to justify the effort… However, when you have a cluster of nodes (when scaling horizontally) or use Continuous Delivery you need an approach to reproduce environments and Containers is brilliant in this. Moreover, Continuous Delivery reduces the time-to-market (new features can be brought to production faster because the deployment and environment setup is automated), which can be used to convince the management. There are reservations about Containers in strictly regulated domains (like the banking sector): To run a container you need root rights. This can be a problem for some companies, in which the colleagues that are supposed to run and update the application on the production server must not have root rights. It is unclear if the usage of Container agrees with certain security standards which have to be fulfilled (like PCI). In some companies, there is the questionable rule, that only software from official/trusted sources can be installed on the machines. ","date":"14 February 2020","externalUrl":null,"permalink":"/benefits-of-containers/","section":"Articles","summary":"What Are Containers? Containers are a form of operating system virtualization. A single container might be used to run anything from a small microservice or software process to a larger application. Inside a container are all the necessary executables, binary code, libraries, and configuration files. Compared to server or machine virtualization approaches, however, containers do not contain operating system images. This makes them more lightweight and portable, with significantly less overhead. In larger application deployments, multiple containers may be deployed as one or more container clusters. Such clusters might be managed by a container orchestrator such as Kubernetes.\n","title":"Benefits of Containers","type":"articles"},{"content":"Working with a good technical architecture you’ll soon need to work with an API Gateway. There are many industrial solutions for large scale system giving full control and logging, such as Apigee or Software AG, but these, of course, cost a business\nIn this article, I’ll look at possible homegrown API’s within ASP.NET Core, which give you a lot of features without the need to pay third parties.\nA very basic API Gateway can be found from Mircea Oprea:\nCreating a simple API Gateway in ASP.NET Core\nHowever, a more production-ready API Gateway to look at is Ocelot\nOcelot Ocelot is a .NET API Gateway. The project is aimed at people using .NET running a micro services/service-oriented architecture that need a unified point of entry into their system. It will work with anything that speaks HTTP and run on any platform that ASP.NET Core supports.\nIt has easy integration with IdentityServer reference and bearer tokens.\nOcelot manipulates the HttpRequest object into a state specified by its configuration until it reaches a request builder middleware where it creates a HttpRequestMessage object which is used to make a request to a downstream service. The middleware that makes the request is the last thing in the Ocelot pipeline. It does not call the next middleware. The response from the downstream service is retrieved as the requests go back up the Ocelot pipeline.\nThere is a piece of middleware that maps the HttpResponseMessage onto the HttpResponse object and that is returned to the client. That is basically it with a bunch of other features!\nFeatures A quick list of Ocelot’s capabilities for more information see the documentation.\nRouting Request Aggregation Service Discovery with Consul \u0026amp; Eureka Service Fabric Kubernetes WebSockets Authentication Authorisation Rate Limiting Caching Retry policies / QoS Load Balancing Logging / Tracing / Correlation Headers / Method / Query String / Claims Transformation Custom Middleware / Delegating Handlers Configuration / Administration REST API Platform / Cloud Agnostic ","date":"12 February 2020","externalUrl":null,"permalink":"/api-gateway-in-asp-net-core/","section":"Articles","summary":"Working with a good technical architecture you’ll soon need to work with an API Gateway. There are many industrial solutions for large scale system giving full control and logging, such as Apigee or Software AG, but these, of course, cost a business\n","title":"API Gateway in ASP.NET Core","type":"articles"},{"content":"","date":"12 February 2020","externalUrl":null,"permalink":"/categories/event-bus/","section":"Categories","summary":"","title":"Event Bus","type":"categories"},{"content":"This article will show how to use an Event Bus using RabbitMQ using Work Queues that will be used to distribute time-consuming tasks among multiple workers.\nGetting started with an Event Bus is fast and easy. This quick start guide uses RabbitMQ with .NET Core. RabbitMQ must be installed, instructions for installing RabbitMQ are included here.\nThe main idea behind Work Queues (aka Task Queues) is to avoid doing a resource-intensive task immediately and having to wait for it to complete. Instead, we schedule the task to be done later. We encapsulate a task as a message and send it to a queue. A worker process running in the background will pop the tasks and eventually execute the job. When you run many workers the tasks will be shared between them.\nThis concept is especially useful in web applications where it’s impossible to handle a complex task during a short HTTP request window.\nThe code is self-explanatory, the NewTask creates 50 tasks on the queue at a time and the Worker will retrieve the queued items, with a 5-second delay – to simulate some work being done.\nRound-robin dispatching One of the advantages of using a Task Queue is the ability to easily parallelise work. If we are building up a backlog of work, we can just add more workers and that way, scale easily.\nTry to run two Worker instances at the same time. They will both get messages from the queue, you will notice that each worker picks new items of the queue. By default, RabbitMQ will send each message to the next consumer, in sequence. On average every consumer will get the same number of messages. This way of distributing messages is called round-robin. Try this out with three or more workers.\nMessage Acknowledgement Doing a task can take a few seconds. You may wonder what happens if one of the consumers starts a long task and dies with it only partly done. With our current code, once RabbitMQ delivers a message to the consumer it immediately marks it for deletion. In this case, if you kill a worker we will lose the message it was just processing. We’ll also lose all the messages that were dispatched to this particular worker but were not yet handled.\nBut we don’t want to lose any tasks. If a worker dies, we’d like the task to be delivered to another worker.\nIn order to make sure a message is never lost, RabbitMQ supports message acknowledgements. An ack(nowledgement) is sent back by the consumer to tell RabbitMQ that a particular message has been received, processed and that RabbitMQ is free to delete it.\nIf a consumer dies (its channel is closed, the connection is closed, or TCP connection is lost) without sending an ack, RabbitMQ will understand that a message wasn’t processed fully and will re-queue it. If there are other consumers online at the same time, it will then quickly redeliver it to another consumer. That way you can be sure that no message is lost, even if the workers occasionally die.\nThere aren’t any message timeouts; RabbitMQ will redeliver the message when the consumer dies. It’s fine even if processing a message takes a very, very long time.\nusing System; using RabbitMQ.Client; using System.Text; namespace RabbitMQ_NewTask { class Program { public static void Main() { var factory = new ConnectionFactory() { HostName = \u0026ldquo;localhost\u0026rdquo; }; using var connection = factory.CreateConnection();\n//Create 50 message on to the Queue for processing for (int i = 0; i \u0026amp;lt; 50; i++) { using (var channel = connection.CreateModel()) { // We make the queue durable so as it remains even after the service restarts channel.QueueDeclare(queue: \u0026quot;RabbitMQ_task_queue\u0026quot;, durable: true, exclusive: false, autoDelete: false, arguments: null); var message = $\u0026quot;Hello World - {i}\u0026quot;; var body = Encoding.UTF8.GetBytes(message); var properties = channel.CreateBasicProperties(); properties.Persistent = true; // This ensures that the message stays on the queue even if a process fails channel.BasicPublish(exchange: \u0026quot;\u0026quot;, routingKey: \u0026quot;RabbitMQ_task_queue\u0026quot;, basicProperties: properties, body: body); Console.WriteLine(\u0026quot; [x] Sent {0}\u0026quot;, message); } } } } }\nNewTask\nusing System; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System.Text; using System.Threading; namespace RabbitMQ_Worker { class Program { public static void Main() { var factory = new ConnectionFactory() { HostName = \u0026ldquo;localhost\u0026rdquo; }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: \u0026ldquo;RabbitMQ_task_queue\u0026rdquo;, durable: true, exclusive: false, autoDelete: false, arguments: null);\nchannel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); Console.WriteLine(\u0026quot; [*] Waiting for messages.\u0026quot;); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) =\u0026amp;gt; { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(\u0026quot; [x] Received {0}\u0026quot;, message); Thread.Sleep(5000); Console.WriteLine(\u0026quot; [x] Done\u0026quot;); channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); }; channel.BasicConsume(queue: \u0026quot;RabbitMQ_task_queue\u0026quot;, autoAck: false, consumer: consumer); Console.WriteLine(\u0026quot; Press [enter] to exit.\u0026quot;); Console.ReadLine(); } } } }\nWorker\nTo get a fuller explanation of this code head over to RabbitMQ tutorials: https://www.rabbitmq.com/tutorials/tutorial-two-dotnet.html\nThe source can be found here:\nhttps://bitbucket.org/bryanavery/rabbitmq\nTo learn more about this you can view the Plural Sight Course\nScaling Applications with Microservices, MassTransit, and RabbitMQ\n","date":"12 February 2020","externalUrl":null,"permalink":"/event-bus-working-sample/","section":"Articles","summary":"This article will show how to use an Event Bus using RabbitMQ using Work Queues that will be used to distribute time-consuming tasks among multiple workers.\nGetting started with an Event Bus is fast and easy. This quick start guide uses RabbitMQ with .NET Core. RabbitMQ must be installed, instructions for installing RabbitMQ are included here.\n","title":"Event Bus Working Sample","type":"articles"},{"content":"I came across this guide as it is an introduction to developing microservices-based applications and managing them using containers. It discusses architectural design and implementation approaches using .NET Core and Docker containers. To make it easier to get started with containers and microservices, the guide focuses on a reference containerized and microservice-based application that you can explore. The sample application is available at the eShopOnContainers GitHub repo. The guide provides foundational development and architectural guidance primarily at a development environment level with a focus on two technologies: Docker and .NET Core. Our intention is that you read this guide when thinking about your application design without focusing on the infrastructure (cloud or on-premises) of your production environment. You will make decisions about your infrastructure later when you create your production-ready applications. Therefore, this guide is intended to be infrastructure agnostic and more development-environment-centric. NET-Microservices-Architecture-for-Containerized-NET-ApplicationsDownload Orignal PDF can be found here:\n","date":"12 February 2020","externalUrl":null,"permalink":"/net-microservices-architecture-for-containerised-net-applications/","section":"Articles","summary":"I came across this guide as it is an introduction to developing microservices-based applications and managing them using containers. It discusses architectural design and implementation approaches using .NET Core and Docker containers. To make it easier to get started with containers and microservices, the guide focuses on a reference containerized and microservice-based application that you can explore. The sample application is available at the eShopOnContainers GitHub repo. ","title":"NET Microservices Architecture for Containerised NET Applications","type":"articles"},{"content":"How do you achieve anonymity between publisher and subscriber? An easy way is to let a middleman take care of all the communication. An event bus is one such middleman.\nAn event bus is typically composed of two parts:\nThe abstraction or interface. One or more implementations. An abstraction of an event bus with multiple implementations based on infrastructure messaging technologies like RabbitMQ, Azure Service Bus, or another event/message broker.\nThe interface should be generic and straightforward, as in the following interface.\npublic interface IEventBus { void Publish(IntegrationEvent @event); void Subscribe\u0026amp;lt;T, TH\u0026amp;gt;() where T : IntegrationEvent where TH : IIntegrationEventHandler\u0026amp;lt;T\u0026amp;gt;; void SubscribeDynamic\u0026amp;lt;TH\u0026amp;gt;(string eventName) where TH : IDynamicIntegrationEventHandler; void UnsubscribeDynamic\u0026amp;lt;TH\u0026amp;gt;(string eventName) where TH : IDynamicIntegrationEventHandler; void Unsubscribe\u0026amp;lt;T, TH\u0026amp;gt;() where TH : IIntegrationEventHandler\u0026amp;lt;T\u0026amp;gt; where T : IntegrationEvent; }\nThe Publish method is straightforward. The event bus will broadcast the integration event passed to it to any microservice, or even an external application, subscribed to that event. This method is used by the microservice that is publishing the event.\nThe Subscribe methods (you can have several implementations depending on the arguments) are used by the microservices that want to receive events. This method has two arguments. The first is the integration event to subscribe to (IntegrationEvent). The second argument is the integration event handler (or callback method), named IIntegrationEventHandler\u0026lt;T\u0026gt;, to be executed when the receiver microservice gets that integration event message.\nYou can see a working example of this here:\nImplementing an event bus with RabbitMQ for the development or test environment\n","date":"12 February 2020","externalUrl":null,"permalink":"/event-bus-interface/","section":"Articles","summary":"How do you achieve anonymity between publisher and subscriber? An easy way is to let a middleman take care of all the communication. An event bus is one such middleman.\nAn event bus is typically composed of two parts:\n","title":"event bus interface","type":"articles"},{"content":"I’m going to take a high-level overview of the Microsoft Azure Service Bus. I’ll discuss briefly the four services that make up the Service Bus. The essence of application integration is software talking to other software. But how should this communication happen? Sometimes, a direct call via API Management is perfect. In other cases, though,\nthis synchronous style of communication won’t work. What if both applications aren’t available at the same time, for instance? For situations like this, an asynchronous approach is required.\nThis kind of communication is exactly what Service Bus provides. Because it lets applications exchange messages through queues, Service Bus allows non-blocking interactions between different chunks of software. Service Bus provides asynchronous communication between all kinds of software\nService Bus provides enterprise messaging among many kinds of software, including cloud applications, on-premises applications, and Azure services. Doing this well requires providing a diverse set of features—it’s harder than you might think. Accordingly, Service Bus provides all the following:\nQueue semantics, including message persistence and strict first-in, first-out ordering of messages. The service also detects and deletes duplicate messages. Atomic transactions, letting a queue read or write be part of a larger operation that succeeds or fails as a single unit. Poison message handling, so a message that causes problems won’t put a receiver into an ongoing loop. High availability, including geo-replication, along with built-in disaster recovery. In short, Service Bus provides all the features required for an enterprise messaging. This Azure service also provides more, however. For example, Service Bus lets a user create one or more topics, then send messages to this topic. Receivers can subscribe to specific topics, then get only the messages sent to that topic. Service Bus lets subscribers selectively receive messages sent to a topic\nAs the figure shows, receivers aren’t required to get every message sent to a particular topic. Instead, each receiver can define filters that determine exactly which message subset they receive. For example, a receiver that subscribed to a topic with messages carrying financial transactions might elect to receive only those messages with an amount of 10,000 Euros or more.\nAsynchronous, message-based communication is an essential aspect of enterprise integration. Service Bus provides this and more like a cloud service on Azure. It’s a fundamental component of Azure Integration Services\nEvent Grid There are lots of integration scenarios in which communication through messages rather than API calls is the best approach. But requiring receiving software to periodically check whether a new message has arrived—commonly known as polling—can be wasteful. Why not let a receiver be notified via an event instead?\nThis is exactly what Event Grid allows. Rather than requiring a receiver to poll for new messages, the receiver instead registers an event handler for the event source it’s interested in. Event Grid then invokes that event handler when the specified event occurs\nEvent Grid invokes receivers when a particular event has occurred.\nAs the figure suggests, many Azure services can generate events. For example, the arrival of a new Service Bus message might cause Event Grid to send a message that starts a Logic App running, or the creation of a new blob in Azure Blob Storage might cause a custom cloud application to begin processing the contents of that blob. Using an event-driven approach can simplify application development, and it can also save money since the receiver needn’t waste cycles polling for new messages.\nTo receive an event from an Azure service, such as Blob Storage, the receiver subscribes to a standard topic provided for that service. But while subscribing to events from Azure services is probably today’s most common use of Event Grid, it’s not the only option. Cloud and on-premises applications can also create custom topics, letting Azure services and other software receive custom events by subscribing to these topics.\nAll of this raises an obvious question: Isn’t Event Grid awfully similar to topics in Service Bus? Why does Azure Integration Services include both? The primary reason is that Service Bus is an enterprise messaging system, with all of the reliability and features that implies, while Event Grid provides only a simple and fast way to send events. Some of the differences that flow from these divergent goals are these:\nService Bus topics work with messages, not events. They let receivers decide when to read a message, and they require the receiver to actively poll for new messages. With Event Grid, events are raised by Azure Blob Storage or something else, then delivered to subscribers. No polling is required to receive these lightweight events. Event Grid is significantly more scalable than Service Bus, supporting up to 10,000,000 events per second in a single Azure region. To achieve this, Event Grid might deliver events out of order, while Service Bus guarantees in-order message delivery. Service Bus is fast, but Event Grid provides near real-time performance, with 99% of events delivered in less than a second. Asynchronous communication is a necessary part of an iPaaS. By providing both Event Grid and Service Bus, Azure Integration Services addresses whatever communication needs your scenario might require.\nThe Microsoft Azure Service Bus is a cloud computing service, and this means a number of things. Firstly, the billing for the service is based on the usage, so with cloud computing, you’re going to be paying for compute instances, data storage, data transfer, and transactions. And with the Azure Service Bus, you don’t pay anything to actually create the messaging entities, it’s when we use those messaging entities and exchange messages on those entities that we’ll incur billing. Cloud computing leverages the Economy of Scale to provide very cost-effective ways of being able to deliver services. There is a lot of infrastructures required to provide the reliable, globally-available Service Bus, and the massive data centres that Microsoft has been provisioning over the past few years allows them to be able to provide us with this infrastructure and charge us for using it.\nAnother thing that’s important today is the Economy of Resources. The data centres provide a lot of power-saving functionality to ensure that both costs and global emissions are kept as low as possible. With cloud computing, the resources are available on-demand, and that means that the provisioning time for creating services is typically measured in minutes, and sometimes it can be seconds. Cloud computing is also self-service, and this means that the consumers of the service are going to be responsible for provisioning and managing the services. We can either do this through a web-based interface or we can use an API to automate the process. Within the data centres, there’s very often no human interaction when we’re creating these services.\nThe Microsoft Azure Service Bus currently offers four technologies.\nRelay Service Brokered Messaging Service Service Bus Event Hubs Service Bus Notification Hubs The Azure Service Bus Relay Service allows clients to expose endpoints in the cloud. The server that’s hosted behind the firewall can make a secure connection to the Relay Service. On receiving this connection, the Relay Service will activate an endpoint for the on-premise service in the cloud. Any client with internet access can then make calls to this endpoint, and the service calls are relayed back to the service host behind the firewall. This provides a very cost-effective way for companies and organizations to expose services, and the applications hosting these services can either be hosted on-premise or in a public or private cloud. The Service Bus Brokered Messaging capabilities allow for durable entities, such as queues and topics, to be created and hosted in Azure Data Centers. In this example, a queue has been created. An application can then connect to the queue and send messages to this queue, and these messages will be stored durably. Receiving applications can then connect to these messaging entities and receive and process the messages. And as with the Relay Service, both the sending applications and the receiving applications can be hosted in the cloud or on-premise. Service Bus Notification Hubs allow messages to be broadcast to a number of devices. Once a Notification Hub is created, an application can send messages to that Notification Hub. We can then have a number of mobile devices that will be receiving those messages. And Notification Hubs provide great scalability, allowing for messages to be broadcast to thousands, and sometimes millions, of devices. Event Hubs provide telemetry services on a massive scale, and they’re typically used for large-scale application telemetry and Internet of Things scenarios. When an Event Hub is created, it can have a number of devices, and these could be applications, they could be console games, they could also be physical devices. These devices can then send telemetry messages to the event hubs, allowing for tens of thousands, and in some cases, millions of messages per second to be received and processed. This course will be focusing entirely on the brokered messaging capabilities of the Service Bus. There are additional courses on Pluralsight that will cover the other services.\nReferences:\nMicrosoft Azure Service Bus Brokered Messaging In-depth\nAzure Integration Services Whitepaper\n","date":"11 February 2020","externalUrl":null,"permalink":"/the-microsoft-azure-service-bus/","section":"Articles","summary":"I’m going to take a high-level overview of the Microsoft Azure Service Bus. I’ll discuss briefly the four services that make up the Service Bus. The essence of application integration is software talking to other software. But how should this communication happen? Sometimes, a direct call via API Management is perfect. In other cases, though,\nthis synchronous style of communication won’t work. What if both applications aren’t available at the same time, for instance? For situations like this, an asynchronous approach is required.\n","title":"The Microsoft Azure Service Bus","type":"articles"},{"content":"I’ve been using an Event Bus for some time now in the designs of a system, for reason of performance and scalability. There is also an issue with the message size. But it would be best if you were using the Event Bus as a messaging system, not a data transport mechanism.\nThere is a solution to this, and it is the claim-check pattern. Split a large message into a claim check and a payload. Send the claim check to the messaging platform and store the payload to an external service. This pattern allows large messages to be processed while protecting the message bus and the client from being overwhelmed or slowed down. This pattern also helps to reduce costs, as storage is usually cheaper than resource units used by the messaging platform.\nContext and problem A messaging-based architecture at some point must be able to send, receive, and manipulate large messages. Such messages may contain anything, including images (for example, MRI scans), sound files (for example, call-centre calls), text documents, or any kind of binary data of arbitrary size.\nSending such large messages to the message bus directly is not recommended, because they require more resources and bandwidth to be consumed. Large messages can also slow down the entire solution because messaging platforms are usually fine-tuned to handle huge quantities of small messages. Also, most messaging platforms have limits on message size, so you may need to work around these limits for large messages.\nSolution Store the entire message payload into an external service, such as a database. Get the reference to the stored payload, and send just that reference to the message bus. The reference acts like a claim check used to retrieve a piece of luggage, hence the name of the pattern. Clients interested in processing that specific message can use the obtained reference to retrieve the payload if needed.\nIssues and considerations Consider the following points when deciding how to implement this pattern:\nConsider deleting the message data after consuming it, if you don’t need to archive the messages. Although blob storage is relatively cheap, it costs some money in the long run, especially if there is a lot of data. Deleting the message can be done synchronously by the application that receives and processes the message, or asynchronously by a separate dedicated process. The asynchronous approach removes old data with no impact on the throughput and message processing performance of the receiving application. Storing and retrieving the message causes some additional overhead and latency. You may want to implement logic in the sending application to use this pattern only when the message size exceeds the data limit of the message bus. The pattern would be skipped for smaller messages. This approach would result in a conditional claim-check pattern. When to use this pattern This pattern should be used whenever a message cannot fit the supported message limit of the chosen message bus technology. For example, Event Hubs currently has a limit of 256 KB (Basic Tier), while Event Grid supports only 64-KB messages.\nThe pattern can also be used if the payload should be accessed only by services that are authorized to see it. By offloading the payload to an external resource, stricter authentication and authorization rules can be put in place, to ensure that security is enforced when sensitive data is stored in the payload.\nWorking Example A good example of this pattern is provided by Microsoft The example is using Blob Store to store data, but any service that supports Event Grid integration can be used too. A client just needs to drop the payload to be shared into the designated Azure Blob Store and Event Grid will automatically generate a Claim Check message and send it to one of the supported message bus. In this sample, the message bus is created using Azure Storage Queues.\nThis allows a client application to poll the queue, get the message and then use the stored reference data to download the payload directly from Azure Blob Storage. The same message, without the need to go through a message bus, can also be directly consumed via Azure Function, leveraging, in this case, the serverless nature of both Azure Event Grid and Azure Functions.\nhttps://github.com/mspnp/cloud-design-patterns/tree/master/claim-check/code-samples/sample-1\nThere are other samples available, but this is the easiest to follow.\nFor more information which out this:\nClaim-Check Pattern by Microsoft using Azure\n","date":"30 January 2020","externalUrl":null,"permalink":"/claim-check-pattern/","section":"Articles","summary":"I’ve been using an Event Bus for some time now in the designs of a system, for reason of performance and scalability. There is also an issue with the message size. But it would be best if you were using the Event Bus as a messaging system, not a data transport mechanism.\n","title":"Claim-Check Pattern","type":"articles"},{"content":"A good API design is important in a system architecture because all data exchange between services happens either through messages or API calls. APIs must be efficient to avoid creating chatty I/O. Because services are designed by teams working independently, APIs must have well-defined semantics and versioning schemes, so that updates don’t break other services.\nIt’s important to distinguish between two types of API:\nPublic APIs that client applications call. Backend APIs that are used for interservice communication. These two use cases have somewhat different requirements. A public API must be compatible with client applications, typically browser applications or native mobile applications. Most of the time that means the public API will use REST over HTTP. For the backend APIs, however, you need to take network performance into account. Depending on the granularity of your services, inter-service communication can result in a lot of network traffic. Services can quickly become I/O bound. For that reason, considerations such as serialization speed and payload size become more important. Some popular alternatives to using REST over HTTP include RPC, Apache Avro, and Apache Thrift. These protocols support binary serialization and are generally more efficient than HTTP.\nSource: Designing APIs for microservices\n","date":"29 January 2020","externalUrl":null,"permalink":"/designing-apis/","section":"Articles","summary":"A good API design is important in a system architecture because all data exchange between services happens either through messages or API calls. APIs must be efficient to avoid creating chatty I/O. Because services are designed by teams working independently, APIs must have well-defined semantics and versioning schemes, so that updates don’t break other services.\n","title":"Designing APIs","type":"articles"},{"content":"Next-Generation Application Development The world of IT infrastructure has evolved dramatically since the days of relying solely on bare metal hardware to support application development. In the early 2000s, a company called VMWare broke the mould, giving rise to virtualization — using an abstraction that makes software (virtual machines) look and behave like hardware. The primary difference between virtualization and bare metal is the inherent benefit of using software to “virtualize” infrastructure. Virtualization offers increased flexibility, scalability, reliability, and often overall capability and performance, all while lowering capital and operational expenses. Containers are a more efficient way of packaging software — including all the elements needed to run the software, such as code, runtime, system tools, system libraries, and settings. With containers, all the moving parts and dependencies across various infrastructure, become less complex and obvious, enabling developers to work with identical development environments and stacks. Abstraction layers: From servers, to VM, to Containers Virtual Machines, but Better There are many parallels between the rise of virtual machines and the rise of containers. Containers are transforming the way in which software is developed in the same way that virtualization and virtual machines did in the early and mid-2000s. There are many benefits to using containers. First, DevOps teams benefit greatly due to the more efficient approach to software development. Containers allow engineering teams to be more agile by reducing wasted resources and empowering teams to build and share code more rapidly in the form of microservices. On top of this, containerization improves scalability through a more lightweight and resource-efficient approach. This improved scalability, coupled with the improvements in development efficiency and velocity, results in greater time and cost efficiencies. Containers are highly flexible and scalable. With containers, we can leverage more processes on each virtual machine and increase its efficiency. We can also run any sort of workload within a container because it is isolated, which ensures that each workload is protected from the others. As a result, a container cannot destroy or impact another container. Ease of use is another core benefit of containers. Similar to how virtual machines were easier to create, scale, and manage compared to physi- cal hardware, containers make it even easier to build software than virtual machines because they can start up in a few seconds. Gone are the days of running the heavy load of processes required by a full virtual machine. Instead, a container affords us the luxury of running a light- weight, isolated process on top of our existing virtual machine. This allows us to quickly and easily scale without getting bogged down with DevOps busy work. The Next Frontier: Container Orchestration As container adoption has exploded, so has the adoption of container orchestration. This again parallels the virtualization world where companies like VMWare offer the necessary tools to launch, monitor, create, and destroy virtual machines. Much like virtual machines, containers need to be monitored and orchestrated to ensure the underlying virtual machines are working properly. Container orchestration allows developers to better track, schedule and operationalize various containers at scale. If we want to run multiple containers across multiple servers and virtual machines — which we’ll need to do if we’re using microservices — this would require otherwise require substantial DevOps resources to make a reality. The many moving parts require us to answer several questions, such as when to start the right containers, how to ensure the containers can talk to each other, what the storage considerations are, and how to ensure high availability across our infrastructure? There’s no wonder the term used to do all of this is “container orchestration”. Fortunately, there are tools designed to do just this — removing the complexity of orchestrating our container executions on the underlying virtual machines, much like how AWS makes it simple to provision EC2 instances. We just create an instance on-demand when needed. We don’t have to worry about the infrastructure issues such as what physical hardware it’s going to be executed on. Likewise, containers and orchestration tools allow us to start new containers without having to worry about what underlying virtual machine is going to take that workload. For example, a container orchestration tools such as Kubernetes will do things like deciding if a virtual machine is underutilized and then decide to run a container on that virtual machine over another. Kubernetes: Modern Infrastructure for Modern Applications what exactly is Kubernetes? Started by Google in 2014, Kubernetes is an open-source project that focuses on building a robust orchestration system for running thousands of containers in production. Through automation of these processes, Kubernetes can eliminate many of the painful manual tasks and infrastructure complexity that often fall on DevOps teams to help with the deployment, scaling, and management of containerized applications. Kubernetes allows us to not only easily run containers but also to easily run different kinds of workloads alongside our containers. The key to the rise of Kubernetes is in its ability to understand that, when you are running a system, it’s not just about running a container. Furthermore, not every container is the same. A container can be a web app, or it can be something that needs to store data persistently. Common questions that are addressed by Kubernetes include: How do we design applications that may consist of many moving parts, but can still be easily deployed and orchestrated? How can we design applications that can be easily moved from one cloud to another? How can we keep storage consistent with multiple instances of an application? How can we ensure the load is evenly distributed across all containers? How can we reuse our existing technical skills and techniques on application development and design without deep diving into other areas that can slow us down? Even with the rise of Kubernetes as the de facto container orchestration system, there are still some misconceptions on what it is. First off, many folks initially do not understand the difference between Docker and Kubernetes. Simply put, Docker is a tool used to create containers whereas Kubernetes provides the management of those Docker containers. Another misunderstanding is that Kubernetes is not a platform as a service (PaaS), however we can use it as the foundation to develop a PaaS if we want. How Kubernetes Gets Work Done Within Kubernetes, each node runs several services and a Docker engine either in a virtualized environment or a physical server. There are two types of nodes: a master node which serves as the controller of a given cluster and worker nodes which are used to run or host our services represented as containers. Within a worker node, we have the concept of a “pod” which represents a unit of work or collection of containers that are deployed to the same host. Usually, we will run a single container or service inside of a pod. However, there are instances where it makes sense to run several containers inside the same pod if they are tightly coupled together. Kubernetes then connects our pod to your environment and manages our pod, including scaling, rolling deployments and monitoring. Pods have their own IP addresses which means that applications can easily find our service through Kubernetes service discovery. Next up is the notion of a “service”. A service groups together logical collections of pods that perform the same function to present them as a single entity. When a service is created, all the nodes of a cluster are made aware of that new service. What is does is provide a single point of access which makes it easier to facilitate communications between a collection of pods. The deployment of a service simplifies our container design and makes it easier for a user to discover containers. A “label” is an organizational concept that creates a metadata tag for Kubernetes resources for easy searchability. This allows developers to easily query based on how they are labelled. Since a host of Kubernetes functionalities rely on querying the clusters for certain resources, the ability to label resources is critical to ensure developer efficiency. Labels are fundamental to how both services and replication controllers function. A volume represents a location where containers can access and store information. For the application, the volume appears as part of the local filesystem. But volumes may be backed by local storage, Ceph, Gluster, Elastic Block Storage, and several other storage backends. A namespace functions as a grouping mechanism inside of Kubernetes. Services, pods, replication controllers, and volumes can easily cooperate within a namespace, but the namespace provides a degree of isolation from the other parts of the cluster. A replication controller is designed to maintain as many pods that have been requested by a user — allowing for easy scaling. If a container goes down, the replication controller will start up another container, ensuring that there are always the correct number of replica pods available. The Container Orchestration Landscape There are a couple of tools that also provide container orchestration capabilities. The two biggest players competing with Kubernetes are Docker Swarm and Mesosphere DC/OS. Docker Swarm is an easier-to-use option, which hits Kubernetes where they receive the most criticism around being very complex to deploy and manage. Mesosphere DC/OS is a container orchestrator that was designed for big data. It was designed to run containers alongside other workloads such as machine learning and big data and offers integrations with related tools such as Apache Spark and Apache Cassandra. Overall, Kubernetes is currently the most mature and popular out of\nthe three as evidenced by the number of community contributors and enterprise adoption. The keys to their success have been their ability to provide not only the building blocks for launching containers and monitoring those containers, but they have also focused their efforts on creating different sets of container use cases on top of their platform to address different types of advanced workloads. In Kubernetes for example, we can find native objects, native entities within the system that allow us to start a daemon, or to start a container, or to start a database. For other solutions, there is no distinguishing between containers that are running something that could be destroyed at any time. How Kubernetes is Changing Microservices Architectures The impact of a microservices framework to the development of IT solutions in today’s enterprises is clear. At a high level, microservices allow for applications to be engineered into smaller, independent services, that are not dependent upon a specific coding language. This means that when we are building a monolithic application, a microservices architecture allows an engineering organization to decouple the application into disparate components that are not dependent on each other. Instead, the components can be combined to offer the full breadth of functionality of that monolithic application. These components or microservices communicate with each other through an API. And since it is not dependent on a programming language, we can have multiple teams building various components across languages without any compatibility issues. For example, we can have a team running a microservice in Ruby with a container running on Kubernetes communicate seamlessly with a microservice built-in Python running in a container via Kubernetes. As we adopt a microservices architecture, it’s also important to figure out how to monitor across the different services. This is where Kubernetes and its growing ecosystem of tools come into the picture. Kubernetes provides organizations with more options to transition from virtual machines to containers. Kubernetes has done a great job promoting an ecosystem around itself so that when we use Kubernetes, we know that out of the box, there are monitoring tools, CI/CD tools, and many platforms all that natively support Kubernetes. As a result, the decision to use Kubernetes is not solely based on\nwhich container orchestration tool to use to further an organization’s microservices strategy. What organizations are considering is also what the complementary ecosystem of tools looks like. The Kubernetes ecosystem offers all the building blocks for everything we need to leverage containers to build out a rock-solid microservices architecture. The Future is Bright Containers are quickly enveloping the world of software development. And the momentum behind Kubernetes as the future of infrastructure is not slowing down any time soon. It has become the go-to container orchestrator through its deep expertise, enterprise adoption, and robust ecosystem. With a growing number of contributors and IT service providers backing the framework, Kubernetes will continue to improve and expand upon its functionality, the types of applications it can support, and integrations with the overarching ecosystem Information brought together from various sources, main one being konghq.com\n","date":"27 January 2020","externalUrl":null,"permalink":"/kubernetes/","section":"Articles","summary":"Next-Generation Application Development The world of IT infrastructure has evolved dramatically since the days of relying solely on bare metal hardware to support application development. In the early 2000s, a company called VMWare broke the mould, giving rise to virtualization — using an abstraction that makes software (virtual machines) look and behave like hardware. The primary difference between virtualization and bare metal is the inherent benefit of using software to “virtualize” infrastructure. Virtualization offers increased flexibility, scalability, reliability, and often overall capability and performance, all while lowering capital and operational expenses. ","title":"Kubernetes","type":"articles"},{"content":"","date":"27 January 2020","externalUrl":null,"permalink":"/categories/kubernetes/","section":"Categories","summary":"","title":"Kubernetes","type":"categories"},{"content":"","date":"24 January 2020","externalUrl":null,"permalink":"/categories/queue/","section":"Categories","summary":"","title":"Queue","type":"categories"},{"content":"","date":"24 January 2020","externalUrl":null,"permalink":"/categories/signalr/","section":"Categories","summary":"","title":"SignalR","type":"categories"},{"content":"Places I have been working they have banded the use of WebSockets to pushing data to the end-user, or devices. I want to delve into the concept of WebSocket introduced in HTML 5, security issues around the WebSocket model, and the best practices that should be adopted to address security issues around WebSocket. Why Websocket and Not HTTP? In earlier times, the client-server model was built with client requests the server for a resource. The Web was built for this kind of model, and HTTP was sufficient to handle these requests. However, with new advancements of technologies, needs of online gaming and real-time applications have marked the need for a protocol that could provide a bidirectional connection between client and server to allow live streaming.\nWeb applications have grown up a lot and are now consuming more data than ever before. The biggest thing holding them back was the traditional HTTP model of client-initiated transactions. To overcome this, many different strategies were devised to allow servers to push data to the client. One of the most popular of these strategies as long-polling. This involves keeping an HTTP connection open until the server has some data to push down to the client.\nThe problem with all of these solutions is that they carry the overhead of HTTP. Every time you make an HTTP request, a bunch of headers and cookie data are transferred to the server. Initially, HTTP was thought to be modified to create a bidirectional channel between client and server. Still, this model could not sustain because of the HTTP overhead and would undoubtedly introduce latency. But in real-time applications, especially gaming applications, latency cannot be afforded. Because of this shortcoming of HTTP, a new protocol is known as WebSocket, which runs over the same TCP/IP model, was designed.\nHow WebSockets Work WebSockets provide a persistent connection between client and server that both parties can use to start data at any time. The connection is initiated from the client through a WebSocket handshake. This happens over a normal HTTP request packet with an “Upgrade” header. A sample connection is shown below:\nLater, if the server supports the WebSocket connections, then the server responds with an “Upgrade” header in the response. A sample is below:\nAfter an exchange of these request and response messages, a persistent WebSocket connection is established between a client and a server.\nWebSockets can transfer as much data as you like without incurring the overhead associated with traditional HTTP requests. Information is transferred through a WebSocket as messages, each of which consists of one or more frames containing the data you are sending (the payload). To ensure the message can be appropriately reconstructed when it reaches the client, each frame is prefixed with 4-12 bytes of data about the payload. Using this frame-based messaging system helps to reduce the amount of non-payload data that is transferred, leading to significant reductions in latency.\nNote: the “Upgrade” header tells the server that the client wants to initiate a WebSocket connection.\nWebSocket Security Issues WebSocket has some inherent security issues. Some of them are listed below:\nOpen to DOS attack: WebSocket allows an unlimited number of connections to the target server and thus resources on the server can be exhausted because of DOS attack. The WebSocket protocol does not give any particular way to allow a server to authenticate the clients during the handshake process. WebSocket has to take forward only the mechanism available to normal HTTP connections such as cookies, HTTP authentication or TLS authentication. It has been seen that during the upgrade handshake from HTTP to WebSocket (WS), HTTP sends all the authentication information to WS. This attack has been termed as Cross-Site WebSocket Hijacking (CSWSH). WebSockets can be used over unencrypted TCP channels, which can lead to major flaws such as those listed in OWASP Top 10 A6-Sensitive Data Exposure. WebSockets are vulnerable to malicious input data attacks, therefore leading to attacks like Cross-Site Scripting (XSS). The WebSocket protocol implements data masking which is present to prevent proxy cache poisoning. But it has a dark side: masking inhibits security tools from identifying patterns in the traffic. Products such as Data Loss Prevention (DLP) software and firewalls are typically not aware of WebSockets, so they can’t do data analysis on WebSocket traffic, and therefore can’t identify malware, malicious JavaScript and data leakage in WebSocket traffic. The Websocket protocol doesn’t handle authorization and/or authentication. Application-level protocols should handle that separately in a case sensitive data is being transferred. It’s relatively easy to tunnel arbitrary TCP services through a WebSocket, for example, tunnel a database connection directly through to the browser. This is of high risk, as it would enable access to services to an in-browser attacker in the case of a Cross-Site Scripting attack, thus allowing an escalation of an XSS attack into a complete remote breach. Recommendations around WebSockets Security flaws Below are the recommendations / best practices around the security flaws listed above:\nThe WebSocket standard defines an Origin header field which Web browsers set to the URL that originates a WebSocket request. This can be used to differentiate between WebSocket connections from different hosts, or between those made from a browser and some other kind of network client. However, the Origin header is essentially advisory: non-browser clients can easily set the Origin header to any value, and thus “pretend” to be a browser. Origin headers are roughly analogous to the X-Requested-With header used by AJAX requests. Web browsers send a header of X-Requested-With: XMLHttpRequest which can be used to distinguish between AJAX requests made by a browser and those made directly. However, this header is easily set by non-browser clients and thus isn’t trusted as a source of authentication. Use session-individual random tokens (like CSRF-Tokens) on the handshake request and verify them on the server. Websockets must be configured to use secure TCP channel. URI with syntax wss:// illustrates the usage of secure WebSocket connection. Any data from untrusted sources must not be trusted. All input must be sanitized before it goes in the execution context. You should apply equal suspicion to data returned from the server as well. Always process messages received on the client-side as data. Don’t try to assign them directly to the DOM, nor evaluate as code. If the response is JSON, always use JSON.parse() to safely parse the data. Avoid tunnelling if at all possible, instead of developing more secured and checked protocols on top of WebSockets. References An Introduction to WebSockets WebSocket Security WebSocket Security Issues ","date":"24 January 2020","externalUrl":null,"permalink":"/websocket-security-issues/","section":"Articles","summary":"Places I have been working they have banded the use of WebSockets to pushing data to the end-user, or devices. I want to delve into the concept of WebSocket introduced in HTML 5, security issues around the WebSocket model, and the best practices that should be adopted to address security issues around WebSocket. ","title":"WebSocket Security Issues","type":"articles"},{"content":"What are Push Notifications? A notification is a message that pops up on the user’s device. Notifications can be triggered locally by an open application, or they can be “pushed” from the server to the user even when the app is not running. They allow your users to opt-in to timely updates and allow you to effectively re-engage users with customised content.\nWhy WebSockets? Every time I worked on a project where we had to implement any kind of a “real-time” component, usually a chat or an event feed, the word WebSockets started to circulate. Though, most people use them because they either aren’t aware of the alternatives, or they blindly follow other people’s examples.\nWebSockets enable the server and client to send messages to each other at any time, after a connection is established, without an explicit request by one or the other. This is in contrast to HTTP, which is traditionally associated with the challenge-response principle — where to get data one has to explicitly request it. In more technical terms, WebSockets enable a full-duplex connection between the client and the server.\nIn a challenge-response system, there is no way for clients to know when new data is available for them (except by asking the server periodically —polling or long polling), with Websockets the server can push new data at any time which makes them the better candidate for “real-time” applications.\nIt’s important to note that WebSockets convert their HTTP connection to a WebSocket connection. In other words, a WebSocket connection uses HTTP only to do the initial handshake (for authorization and authentification), after which the TCP connection is utilized to send data via its own protocol (hybd).\nAnimation of a WebSocket connection being established\nWebSockets are a part of the HTML5 spec and they are supported by all modern browsers (meaning, there is a JS API to use them natively in the browser). They provide a mechanism to detect dropped (disconnected) clients and can handle up to 1024 connections per browser, though they aren’t compatible with most load balancers out-of-the-box and have no re-connection handling mechanism.\nThe most common example for WebSockets is either a chat or push notifications. They can be used for those applications, but present an overkill solution to the problem, since in those applications only the server needs to push data to the clients, and not the other way around — only a half-duplex connection is needed.\nGood reference are:\nIntroduction to Push Notifications Do you really need WebSockets? SignalR the right way Web Push Notifications: Timely, Relevant, and Precise ","date":"24 January 2020","externalUrl":null,"permalink":"/push-notifications/","section":"Articles","summary":"What are Push Notifications? A notification is a message that pops up on the user’s device. Notifications can be triggered locally by an open application, or they can be “pushed” from the server to the user even when the app is not running. They allow your users to opt-in to timely updates and allow you to effectively re-engage users with customised content.\n","title":"Push Notifications","type":"articles"},{"content":"","date":"24 January 2020","externalUrl":null,"permalink":"/categories/microservice/","section":"Categories","summary":"","title":"Microservice","type":"categories"},{"content":"In an event-driven architecture, when a service performs some piece of work that other services might be interested in, that service produces an event—a record of the completed action. Other services consume those events so that they can perform any of their tasks needed as a result of the event. Unlike with REST, services that create requests do not need to know the details of the services consuming the requests. Here’s a simple example: When an order is placed on an e-commerce site, a single “order placed” event is produced and then consumed by several microservices:\nthe order service which could write an order record to the database the customer service which could create the customer record, and the payment service which could process the payment. Events can be published in a variety of ways. For example, they can be published to a queue that guarantees delivery of the event to the appropriate consumers, or they can be published to a “pub/sub” model stream that publishes the event and allows access to all interested parties. In either case, the producer publishes the event, and the consumer receives that event, reacting accordingly. Note that in some cases, these two actors can also be called the publisher (the producer) and the subscriber (the consumer).\nWhy Use Event-Driven Architecture An event-driven architecture offers several advantages over REST, which include:\nAsynchronous – event-based architectures are asynchronous without blocking. This allows resources to move freely to the next task once their unit of work is complete, without worrying about what happened before or will happen next. They also allow events to be queued or buffered which prevents consumers from putting back pressure on producers or blocking them. Loose Coupling – services don’t need (and shouldn’t have) knowledge of, or dependencies on other services. When using events, services operate independently, without knowledge of other services, including their implementation details and transport protocol. Services under an event model can be updated, tested, and deployed independently and more easily. Easy Scaling – Since the services are decoupled under an event-driven architecture, and as services typically perform only one task, tracking down bottlenecks to a specific service, and scaling that service (and only that service) becomes easy. Recovery support – An event-driven architecture with a queue can recover lost work by “replaying” events from the past. This can be valuable to prevent data loss when a consumer needs to recover. Of course, event-driven architectures have drawbacks as well. They are easy to over-engineer by separating concerns that might be simpler when closely coupled; can require significant upfront investment; and often result in additional complexity in infrastructure, service contracts or schemas, polyglot build systems, and dependency graphs. Perhaps the most significant drawback and the challenge is data and transaction management. Because of their asynchronous nature, event-driven models must carefully handle inconsistent data between services, incompatible versions, watch for duplicate events, and typically do not support ACID transactions, instead of supporting eventual consistency which can be more difficult to track or debug. Even with these drawbacks, an event-driven architecture is usually the better choice for enterprise-level microservice systems. The pros—scalable, loosely coupled, dev-ops friendly design—outweigh the cons. When to Use REST There are, however, times when a REST/web interface may still be preferable:\nYou need a time-bound request/reply interface Convenient support for transactions Your API is available to the public Your project is small (REST is much simpler to set up and deploy) Your Most Important Design Choice – Messaging Framework Once you’ve decided on an event-driven architecture, it is time to choose your event framework. The way your events are produced and consumed is a key factor in your system. Dozens of proven frameworks and choices exist and choosing the right one takes time and research. Your basic choice comes down to message processing or stream processing. Message Processing In traditional message processing, a component creates a message then sends it to a specific (and typically single) destination. The receiving component, which has been sitting idle and waiting, receives the message and acts accordingly. Typically, when the message arrives, the receiving component performs a single process. Then, the message is deleted.\nOriginal article - Best Practices for Event-Driven Microservice Architecture ","date":"24 January 2020","externalUrl":null,"permalink":"/what-is-event-driven-microservice-architecture/","section":"Articles","summary":"In an event-driven architecture, when a service performs some piece of work that other services might be interested in, that service produces an event—a record of the completed action. Other services consume those events so that they can perform any of their tasks needed as a result of the event. Unlike with REST, services that create requests do not need to know the details of the services consuming the requests. Here’s a simple example: When an order is placed on an e-commerce site, a single “order placed” event is produced and then consumed by several microservices:\n","title":"What is Event-Driven Microservice Architecture?","type":"articles"},{"content":" (Avoid shared databases). When multiple services consume a shared data schema, it can create tight coupling at the data layer. To avoid tight coupling, each service should have its data access logic and separate data store. The development team is free to pick the data persistence method which best fit each service and nature of data.\nAvoid shared data stores and data access mechanisms (Image: christianposta.com)\n","date":"23 January 2020","externalUrl":null,"permalink":"/decentralized-data-management/","section":"Articles","summary":" (Avoid shared databases). When multiple services consume a shared data schema, it can create tight coupling at the data layer. To avoid tight coupling, each service should have its data access logic and separate data store. The development team is free to pick the data persistence method which best fit each service and nature of data.\n","title":"Decentralised Data Management","type":"articles"},{"content":"API Gateway API Gateway acts as a single entry point for all clients with a more critical role as an edge service for exposing microservices to the outside world as managed APIs. It sounds like a reverse proxy, but also has additional responsibilities like simple load-balancing, authentication \u0026amp; authorization, failure handling, auditing, protocol translations, and routing. There are several ways in which the API Gateway can be deployed from a development perspective.\nAPI Gateway Style Microservices Architecture (Image: Microsoft Azure Docs)\nBuild it programmatically — to have better customizations and control Deploy an existing API gateway product, (such as Apigee) — to save initial development time and use advanced built-in features Some design patterns that explain API Gateway behaviour are as follows (Read Design patterns for microservices).\nGateway Aggregation — aggregate multiple client requests (usually HTTP requests) targeting multiple internal microservices into a single client request, reducing chattiness and latency between consumers and services. Gateway Offloading— enable individual microservices to offload their shared service functionality to the API gateway level. Such cross-cutting functionalities include authentication, authorization, service discovery, fault tolerance mechanisms, QoS, load balancing, logging, analytics etc. Gateway Routing (layered routing, usually HTTP requests)— route requests to the endpoints of internal microservices using a single endpoint, so that consumers don’t need to manage many separate endpoints Note that an API Gateway should always be a highly-available and performant component since it is the entry point to the entire system.\nSmart endpoints and dumb pipes Each service owns a well-defined API for external communication. Avoid leaking implementation details. For communication, always use simple protocols such as REST over HTTP.\nAsynchronous communication When asynchronous communication is used across services, the data flow does not get blocked for other services.\nAvoid coupling between services Services should have loose coupling and high functional cohesion. The main causes of coupling include shared database schemas and rigid communication protocols.\nDecentralize development Avoid sharing codebases, data schemas, or development team members among multiple services/projects. Let developers focus on innovation and quality at the source.\nKeep domain knowledge out of the gateway. Let the gateway handle routing and cross-cutting concerns (authentication, SSL termination).\nToken-based Authentication Instead of implementing security components at each microservices level which is talking to a centralized/shared user repository and retrieve the authentication information, consider implementing authentication at API Gateway level with widely-used API security standards such as OAuth2 and OpenID Connect. After obtaining an auth token from the auth provider, it can be used to communicate with other microservices.\nMicroservice security with OAuth2 and OpenID Connect (Image: Kasun’s Blog)\nEvent-driven nature Human beings are autonomous agents that can react to events. Can’t our systems be like that? (Read: Why Microservices Should Be Event-Driven: Autonomy vs Authority)\nFault tolerance Since the system comprises of multiple services and middleware components, failures can take place somewhere very easily. Implementing patterns like circuit-breaking, bulkhead, retries, timeouts, fail fast, failover caching, rate limiters, load shedders in such vulnerable components can minimize the risks of major failures. (Read: Designing a Microservices Architecture for Failure)\nProduct engineering Microservices will work well as long as it is engineered as a product, not as a project. It’s not about making it work somehow and delivering before the deadlines, but about a long term commitment of engineering excellence.\nContent originally from Thilina Ashen Gamage ","date":"20 January 2020","externalUrl":null,"permalink":"/microservices-best-practices/","section":"Articles","summary":"API Gateway API Gateway acts as a single entry point for all clients with a more critical role as an edge service for exposing microservices to the outside world as managed APIs. It sounds like a reverse proxy, but also has additional responsibilities like simple load-balancing, authentication \u0026 authorization, failure handling, auditing, protocol translations, and routing. There are several ways in which the API Gateway can be deployed from a development perspective.\n","title":"Microservices Best Practices","type":"articles"},{"content":"","date":"20 January 2020","externalUrl":null,"permalink":"/categories/patterns/","section":"Categories","summary":"","title":"Patterns","type":"categories"},{"content":"Microservices is a trending topic among software engineers today, why is this? In this post, I’ll endeavour to take the mystery and explain things in plain English so you can build genuinely modular, business agile IT systems with Microservices architectural style.\nThe goal of microservices is to increase the velocity of application releases, by decomposing the application into small autonomous services that can be deployed independently. Microservices Architecture Microservices architecture consists of collections of light-weight, loosely-coupled services. Each service implements a single business capability. Ideally, these services should be cohesive enough to develop, test, release, deploy, scale, integrate, and maintain independence.\nFormal Definition “Microservice architectural style is an approach to developing a single application as a suite of small services, each running in its process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies.”- James Lewis and Martin Fowler Defining Characteristics of Microservices Each service is a light-weight, independent, and loosely-coupled business unit. Each service has its own codebase, managed and developed by a small team (mostly in an agile environment). Each service is responsible for a single part of the functionality (business capability) and does it well. Each service can pick the best technology stack for its use cases (no need to stick into one framework throughout the entire application). Each service has its own DevOp plan (test, release, deploy, scale, integrate, and maintain independently). Each service is deployed in a self-contained environment. Services communicate with each other by using well-defined APIs (smart endpoints) and simple protocols like REST over HTTP (dumb pipes). Each service is responsible for persisting its own data and keeping external state (Only if multiple services consume the same data, such situations are handled in a common data layer). Benefits of Microservices Microservice is made to scale large systems. They are great enablers for continuous integration and delivery too.\nThe Scale Cube: 3-Dimensional Model for Scalability (Image: Nginx Blog)\nIndependent scaling — Microservices architecture supports Scale Cube concept described in the excellent book The Art of Scalability. When developing microservices to achieve functional decomposition, the application automatically scales via the Y-axis. When the consumption is high, microservices can scale via the X-axis by cloning with more CPU and memory. For distributing data across multiple machines, large databases can be separated (sharding) into smaller, faster, more easily managed parts enabling Z-axis scaling.\nIndependent releases and deployments — Bug fixes and feature releases are more manageable and less risky, with microservices. You can update a service without redeploying the entire application, and roll back or roll forward an update if something goes wrong. Independent development — Each service has its codebase, which is developed, tested, and deployed by a small, focused team. Developers can focus on one service and relatively-small scope only. This results in enhanced productivity, project velocity, continuous innovation, and quality at source. Graceful degradation — If a service goes down, its impact won’t propagate to the rest of the application and result in a catastrophic failure of the system, allowing a certain degree of anti-fragility to manifest. Decentralized governance — Developers are free to pick the technology stacks and make design standards and implementation decisions that are best suited for their service. Teams do not have to get penalized due to past technology decisions. Operational Concerns Independent services alone cannot form a system. For the real success of microservices architecture, significant investments are required to handle cross-system concerns like:\nService replication — a mechanism by which services can easily scale based upon metadata Service registration and discovery — a mechanism to enables service lookup and finds the endpoint for each service Service monitoring and logging — a mechanism to aggregate logs from different microservices and provide a consistent reporting Resiliency — a mechanism for services to automatically take corrective actions during failures DevOps — a mechanism for handling continuous integration and deployment (CI and CD) API gateway — a mechanism for providing an entry point for clients Reference Microservices Design Guide\n","date":"20 January 2020","externalUrl":null,"permalink":"/microservices/","section":"Articles","summary":"Microservices is a trending topic among software engineers today, why is this? In this post, I’ll endeavour to take the mystery and explain things in plain English so you can build genuinely modular, business agile IT systems with Microservices architectural style.\n","title":"Microservices","type":"articles"},{"content":"Docker’s containers allow for the immense economy of scale and have made development scalable, while at the same time keeping the process user-friendly.\nLet’s get to work and see what it is all about, we’ll go over the following:\nWhat Docker is and how you can use it in your own DevOps environment How Docker compares with traditional virtual machines Why Docker is better than a virtual environment Advantages of working with Docker How to build a Docker environment Basic and advanced components of Docker Some basic commands—and you can watch a live demo Docker vs Virtual Machines\nMajor differences are you’ll notice some major differences, including:\nThe virtual environment has a hypervisor layer, whereas Docker has a Docker engine layer. There are additional layers of libraries within the virtual machine, each of which compounds and creates very significant differences between a Docker environment and a virtual machine environment. With a virtual machine, the memory usage is very high, whereas, in a Docker environment, memory usage is very low. In terms of performance, when you start building out a virtual machine, particularly when you have more than one virtual machine on a server, the performance becomes poorer. With Docker, the performance is always high because of the single Docker engine. In terms of portability, virtual machines just are not ideal. They’re still dependent on the host operating system, and a lot of problems can happen when you use virtual machines for portability. In contrast, Docker was designed for portability. You can actually build solutions in a Docker container, and the solution is guaranteed to work as you have built it no matter where it’s hosted. The boot-up time for a virtual machine is fairly slow in comparison to the boot-up time for a Docker environment, in which boot-up is almost instantaneous. One of the other challenges of using a virtual machine is that if you have unused memory within the environment, you cannot reallocate it. If you set up an environment that has 9 gigabytes of memory, and 6 of those gigabytes are free, you cannot do anything with that unused memory. With Docker, if you have free memory, you can reallocate and reuse it across other containers used within the Docker environment. Another challenge of virtual machines is that running multiples of them in a single environment can lead to instability and performance issues. Docker, on the other hand, is designed to run multiple containers in the same environment—it actually gets better with more containers run in that hosted single Docker engine. Virtual machines have portability issues; the software can work on one machine, but if you move that virtual machine to another machine, suddenly some of the software won’t work, because some dependencies will not be inherited correctly. Docker is designed to be able to run across multiple environments and to be deployed easily across systems. The boot-up time for a virtual machine is about a few minutes, in contrast to the milliseconds it takes for a Docker environment to boot up. What Is Docker? Docker is an OS virtualized software platform that allows IT organizations to easily create, deploy, and run applications in Docker containers, which have all the dependencies within them. The container itself is really just a very lightweight package that has all the instructions and dependencies—such as frameworks, libraries, and bins—within it. The container itself can be moved from environment to environment very easily. In a DevOps life cycle, the area where Docker really shines is deployment, because when you deploy your solution, you want to be able to guarantee that the code that has been tested will actually work in the production environment. In addition to that, when you’re building and testing the code, having a container running the solution at those stages is also beneficial because you can validate your work in the same environment used for production. You can use Docker in multiple stages of your DevOps cycle, but it is especially valuable in the deployment stage. Advantages of Docker As noted previously, you can do rapid deployment using Docker. The environment itself is highly portable and was designed with efficiencies that allow you to run multiple Docker containers in a single environment, unlike traditional virtual machine environments. The configuration itself can be scripted through a language called YAML, which allows you to describe the Docker environment you want to create. This, in turn, allows you to scale your environment quickly. But probably the most critical advantage these days is security. You have to ensure that the environment you’re running is highly secure yet highly scalable, and Docker takes security very seriously. You’ll see it as one of the key components of the agile architecture of the system you’re implementing. How Does Docker Work? Docker works via a Docker engine that is composed of two key elements: a server and a client; and the communication between the two is via REST API. The server communicates the instructions to the client. On older Windows and Mac systems, you can take advantage of the Docker Toolbox, which allows you to control the Docker engine using Compose and Kitematic.\nComponents of Docker There are four components that we will discuss:\nDocker client and server Docker image Docker registry Docker container Docker Client and Server This is a command-line-instructed solution in which you would use the terminal on your Mac or Linux system to issue commands from the Docker client to the Docker daemon. The communication between the Docker client and the Docker host is via a REST API. You can issue similar commands, such as a Docker Pull command, which would send an instruction to the daemon and perform the operation by interacting with other components (image, container, registry). The Docker daemon itself is actually a server that interacts with the operating system and performs services. As you’d imagine, the Docker daemon constantly listens across the REST API to see if it needs to perform any specific requests. If you want to trigger and start the whole process, you’ll need to use the Docker command within your Docker daemon, which will start all of your performances. Then you have a Docker host, which lets you run the Docker daemon and registry. Now let’s talk about the actual structure of a Docker image. A Docker image is a template that contains instructions for the Docker container. That template is written in a language called YAML, which stands for Yet Another Markup Language. Docker Image The Docker image is built within the YAML file and then hosted as a file in the Docker registry. The image has several key layers, and each layer depends on the layer below it. Image layers are created by executing each command in the Dockerfile and are in the read-only format. You start with your base layer, which will typically have your base image and your base operating system, and then you will have a layer of dependencies above that. These then comprise the instructions in a read-only file that would become your Dockerfile. Here we have four layers of instructions: From, Pull, Run and CMD. What do actually look like? The From command creates a layer based on Ubuntu, and then we add files from the Docker repository to the base command of that base layer.\nPull: Adds files from your Docker repository Run: Builds your container CMD: Specifies which command to run within the container In this instance, the command is to run Python. One of the things that will happen as we set up multiple containers is that each new container adds a new layer with new images within the Docker environment. Each container is completely separate from the other containers within the Docker environment, so you can create your own separate read-write instructions within each layer. What’s interesting is that if you delete a layer, the layer above it will also get deleted. What happens when you pull in a layer but something changed in the core image? Interestingly, the main image itself cannot be modified. Once you’ve copied the image, you can modify it locally. You can never modify the actual base image.\nDocker Registry The Docker registry is where you would host various types of images and where you would distribute the images from. The repository itself is just a collection of Docker images, which are built on instructions written in YAML and are very easily stored and shared. You can give the Docker images name tags so that it’s easy for people to find and share them within the Docker registry. One way to start managing a registry is to use the publicly accessible Docker hub registry, which is available to anybody. You can also create your own registry for your own use internally.\nThe registry that you create internally can have both public and private images that you create. The commands you would use to connect the registry are Push and Pull. Use the Push command to push a new container environment you’ve created from your local manager node to the Docker registry, and use a Pull command to retrieve new clients (Docker image) created from the Docker registry. Again, a Pull command pulls and retrieves a Docker image from the Docker registry, and a Push command allows you to take a new command that you’ve created and pushed it to the registry, whether it’s Docker hub or your own private registry.\nDocker Container The Docker container is an executable package of applications and its dependencies bundled together; it gives all the instructions for the solution you’re looking to run. It’s really lightweight due to the built-in structural redundancy. The container is also inherently portable. Another benefit is that it runs completely in isolation. Even if you are running a container, it’s guaranteed not to be impacted by any host OS securities or unique setups, unlike with a virtual machine or a non-containerized environment. The memory for a Docker environment can be shared across multiple containers, which is really useful, especially when you have a virtual machine that has a defined amount of memory for each environment. The container is built using Docker images, and the command to run those images is Run. Let’s go through the basic steps of running a Docker image.\nConsider a basic example of Docker run command for starting a single container called redis:\n$ Docker run redis\nIf you don’t have the Redis image locally installed, it will be pulled from the registry. After this, the new Docker container Redis will be available within your environment so you can start using it.\nNow let’s look at why containers are so lightweight. It’s because they do not have some of the additional layers that virtual machines do. The biggest layer Docker doesn’t have is the hypervisor, and it doesn’t need to run on a host operating system.\nAdvanced Docker Components Now we’ll look at two advanced components:\nDocker compose Docker swamp Docker Compose Docker-compose is designed for running multiple containers as a single service. It does so by running each container in isolation but allowing the containers to interact with one another. As noted earlier, you would write the compose environments using YAML.\nSo in what situations might you use Docker compose? An example would be if you are running an Apache server with a single database and you need to create additional containers to run additional services without having to start each one separately. ou would write a set of files using Docker compose to do that.\nDocker Swarm Docker swarm is a service for containers that allows IT administrators and developers to create and manage a cluster of swarm nodes within the Docker platform. Each node of Docker swarm is a Docker daemon, and all Docker daemons interact using the Docker API. A swarm consists of two types of nodes: a manager node and a worker node. A manager node maintains cluster management tasks. Worker nodes receive and execute tasks from the manager node.\nOriginal article: Docker Tutorial – Basic Concepts, Components and Advantages\n","date":"11 January 2020","externalUrl":null,"permalink":"/docker-basic-concepts-components-and-advantages/","section":"Articles","summary":"Docker’s containers allow for the immense economy of scale and have made development scalable, while at the same time keeping the process user-friendly.\nLet’s get to work and see what it is all about, we’ll go over the following:\n","title":"Docker – Basic Concepts, Components and Advantages","type":"articles"},{"content":"What is Docker? It is a hot topic in cloud computing, one that people are finding ample job opportunities with skills in it. But what is Docker used for?\nWhat is Docker? Docker is an open-source technology used mostly for developing, shipping and running applications. With it, you can isolate applications from their underlying infrastructure so that software delivery is faster than ever. Docker’s main benefit is to package applications in “containers,” so they’re portable for any system running the Linux operating system (OS) or Windows OS. Though container technology has been around for a while, the hype around Docker’s approach to containers has moved this approach to the mainstream as one of the most popular forms of container technology. The brilliance of Docker is that, once you package an application and all its dependencies into a Docker run container, you ensure it will run in any environment. Also, DevOps professionals can build applications with Docker and ensure that they will not interfere with each other. As a result, you can build a container having different applications installed on it and give it to your QA team, which will then only need to run the container to replicate your environment. Therefore, using Docker tools saves time. In addition, unlike when using Virtual Machines (VMs), you don’t have to worry about what platform you’re using – Docker containers work everywhere.\nWhat is Docker Container? Now, your intrigue about Docker containers is no doubt piqued. A Docker container, as partially explained above, is a standard unit of software that stores up code and all its dependencies so the application runs fast and reliably from one computing environment to different ones. A Docker container image is a lightweight, standalone, executable package of software that has everything you need to run an application – code, runtime, system tools, system libraries, and settings.\nAvailable for both Linux- and Windows-based applications, containerized software will always run the same, regardless of the infrastructure. Containers isolate software from its environment and ensure that it works uniformly despite differences.\nThe Benefits of Docker Containers Docker containers are popular now because they have Virtual Machines beat. VMs contain full copies of an operating system, the application, necessary binaries, and libraries – taking up tens of GBs. VMs can also be slow to boot. In contrast, Docker containers take up less space (their images are usually only tens of MBs big), handle more applications and use fewer VMs and Operating Systems. Thus, they’re more flexible and tenable. Additionally, using Docker in the cloud is popular and beneficial. In fact, since various applications can run on top of a single OS instance, this can be a more effective way to run them. Isolation and Throttling\nAnother distinct benefit of Docker containers is their ability to keep apps isolated not only from each other but also from their underlying system. This lets you easily dictate how an allocated containerized unit uses its system resources, like its CPU, GPU, and network. It also easily ensures data and code remain separate.\nPortability A Docker container runs on any machine that supports the container’s runtime environment. You don’t have to tie applications to the host operating system, so both the application environment and the underlying operating environment can be kept clean and minimal.\nYou can readily move container-based apps from systems to cloud environments or from developers’ laptops to servers if the target system supports Docker and any of the third-party tools that might be used with it.\nComposability Most business applications consist of several separate components organized into a stack—a web server, a database, an in-memory cache. Containers enable you to compose these pieces into a functional unit with easily changeable parts. A different container provides each piece so each can be maintained, updated, swapped out, and modified independently of the others.\nBasically, this is the microservices model of application design. By dividing application functionality into separate, self-contained services, the model offers an alternative to slow, traditional development processes and inflexible apps. Lightweight, portable containers make it simpler to create and sustain microservices-based applications.\nOriginal Article: What is Docker: Benefits of Docker Container and Reasons to Learn\n","date":"11 January 2020","externalUrl":null,"permalink":"/docker-containers/","section":"Articles","summary":"What is Docker? It is a hot topic in cloud computing, one that people are finding ample job opportunities with skills in it. But what is Docker used for?\nWhat is Docker? Docker is an open-source technology used mostly for developing, shipping and running applications. With it, you can isolate applications from their underlying infrastructure so that software delivery is faster than ever. Docker’s main benefit is to package applications in “containers,” so they’re portable for any system running the Linux operating system (OS) or Windows OS. Though container technology has been around for a while, the hype around Docker’s approach to containers has moved this approach to the mainstream as one of the most popular forms of container technology. ","title":"Docker Containers","type":"articles"},{"content":"Raw System.Text.Json .NET Core 3.0, has shipped with the new System.Text.Json APIs, which provides built-in support for JSON, including reader/writer, read-only DOM, and serializer/deserializer. With the performance, the main improvement to the methods, check and see the typical speedups of up to 2x over Json.NET.\nDoing micro-benchmarks to compare System.Text.Json with Json.NET yields the following output:\nScenario Speed Memory Deserialization 2x faster Parity or lower Serialization 1.5x faster Parity or lower Document (read-only) 3-5x faster ~Allocation free for sizes \u0026lt; 1 MB Reader 2-3x faster ~Allocation free (until you materialize values) Writer 1.3-1.6x faster ~Allocation free ASP.NET Core 3.0 includes support for System.Text.Json, which is enabled by default.\nUsing System.Text.Json directly For all the samples, make sure you import the following two namespaces:\nusing System.Text.Json;\nusing System.Text.Json.Serialization; Using the serializer The System.Text.Json the serializer can read and write JSON asynchronously and is optimized for UTF-8 text, making it ideal for REST API and back-end applications.\nclass WeatherForecast\n{\npublic DateTimeOffset Date { get; set; }\npublic int TemperatureC { get; set; }\npublic string Summary { get; set; }\n} string Serialize(WeatherForecast value)\n{\nreturn JsonSerializer.ToString(value);\n} By default, a minified JSON is produced. To produce something that is human-readable, you can pass in an instance of JsonSerializerOptions to the serializer. This is also the way you configure other settings, such as handling of comments, trailing commas, and naming policies.\nstring SerializePrettyPrint(WeatherForecast value)\n{\nvar options = new JsonSerializerOptions\n{\nWriteIndented = true\n};\nreturn JsonSerializer.ToString(value, options);\n} Deserialization works similarly:\n// { // \"Date\": \"2013-01-20T00:00:00Z\", // \"TemperatureC\": 42, // \"Summary\": \"Typical summer in Seattle. Not.\", // } WeatherForecast Deserialize(string json) { var options = new JsonSerializerOptions { AllowTrailingCommas = true }; return JsonSerializer.Parse(json, options); } The support asynchronous serialization and deserialization:\nasync Task SerializeAsync(WeatherForecast value, Stream stream) { await JsonSerializer.WriteAsync(value, stream); } You can also use custom attributes to control serialization behaviour, for example, ignoring properties and specifying the name of the property in the JSON:\nclass WeatherForecast { public DateTimeOffset Date { get; set; } // Always in Celsius. [JsonPropertyName(\"temp\")] public int TemperatureC { get; set; } public string Summary { get; set; } // Don't serialize this property. [JsonIgnore] public bool IsHot =\u0026gt; TemperatureC \u0026gt;= 30; } Original article can be found here: https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/\n","date":"27 September 2019","externalUrl":null,"permalink":"/high-performance-json-api/","section":"Articles","summary":"Raw System.Text.Json .NET Core 3.0, has shipped with the new System.Text.Json APIs, which provides built-in support for JSON, including reader/writer, read-only DOM, and serializer/deserializer. With the performance, the main improvement to the methods, check and see the typical speedups of up to 2x over Json.NET.\n","title":"High-performance JSON API","type":"articles"},{"content":"","date":"27 September 2019","externalUrl":null,"permalink":"/categories/json/","section":"Categories","summary":"","title":"Json","type":"categories"},{"content":"The new feature Async Streams in C# has removed the scalar result limitation and allows the async method to returns multiple results.\nThis change makes the async pattern more flexible so that you can retrieve data in lazy asynchronous sequence from a database or you can download data from an asynchronous sequence that returns the data in chunks when they become available. Here is an example\nawait foreach (var issue in runPagedQueryAsync(client, PagedIssueQuery, \"docs\")) Console.WriteLine(issue); This makes full use of the service you are calling with the speed and response it was designed for.\nHere is a fully working example that calls the GitHub API Program.cs_Download ","date":"27 September 2019","externalUrl":null,"permalink":"/async-streams/","section":"Articles","summary":"The new feature Async Streams in C# has removed the scalar result limitation and allows the async method to returns multiple results.\nThis change makes the async pattern more flexible so that you can retrieve data in lazy asynchronous sequence from a database or you can download data from an asynchronous sequence that returns the data in chunks when they become available. ","title":"Async Streams","type":"articles"},{"content":" Description It is possible to trick a user into executing potentially dangerous actions against the target site due to a lack of Cross- Site-Request-Forgery (CSRF) protections. CSRF attacks are a class of confused deputy attacks that exploit the behaviour of browsers always sending authorization cookies in requests. The target site has no secure way of verifying the request was initiated from a link on a trusted domain.\nRecommendations Protect all forms by generating a random unique nonce value each time the page is requested. This nonce value should be included in the form as a parameter, usually as a hidden input field. These nonce values should be linked to the user’s session ID and validated on submission by comparing the generated nonce value for the form with the one that was submitted by the user. When possible, use built-in CSRF protections offered by various vetted libraries or frameworks instead of developing a custom implementation.\nIf your deployment is to a stateless environment then you will need to ensure that the state on the server is stored in a central reusable location.\nUseful links:\nPrevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core\n","date":"20 September 2019","externalUrl":null,"permalink":"/cross-site-request-forgery-csrf/","section":"Articles","summary":" Description It is possible to trick a user into executing potentially dangerous actions against the target site due to a lack of Cross- Site-Request-Forgery (CSRF) protections. CSRF attacks are a class of confused deputy attacks that exploit the behaviour of browsers always sending authorization cookies in requests. The target site has no secure way of verifying the request was initiated from a link on a trusted domain.\n","title":"Cross-Site Request Forgery (CSRF)","type":"articles"},{"content":" Description The SSL Certificate Details provide information about the certificate associated with the HTTPS server. This information describes important attributes of the certificate and should be reviewed for the correctness of the contact information, whether it is self-signed, and how soon it will expire. The Supported Ciphers provides information about each available encryption scheme available for each of the possible SSL/TLS protocols.\nRecommendations The expiration date for certificates should be monitored. New certificates should be available before the expiration date in order to maintain continuity of service and avoid downtime or displaying certificate expiration errors in users’ web browsers.\n","date":"20 September 2019","externalUrl":null,"permalink":"/improper-certificate-validation/","section":"Articles","summary":" Description The SSL Certificate Details provide information about the certificate associated with the HTTPS server. This information describes important attributes of the certificate and should be reviewed for the correctness of the contact information, whether it is self-signed, and how soon it will expire. The Supported Ciphers provides information about each available encryption scheme available for each of the possible SSL/TLS protocols.\nRecommendations The expiration date for certificates should be monitored. New certificates should be available before the expiration date in order to maintain continuity of service and avoid downtime or displaying certificate expiration errors in users’ web browsers.\n","title":"Improper Certificate Validation","type":"articles"},{"content":"","date":"19 September 2019","externalUrl":null,"permalink":"/categories/pentest/","section":"Categories","summary":"","title":"Pentest","type":"categories"},{"content":" Description “Server Side Request Forgery” (a.k.a. SSRF) is a class of web-application vulnerability in which an attacker can cause a website to access unintended server-side resources, including the unauthorized reading, writing, or execution of server resources.\nWeb-applications designed to pass URLs (references to server accessible content) or portions thereof, from the client browser to the application server using HTTP request parameters or HTTP request headers, are at risk for Server Side Request Forgery exploitation unless they protect against it.\nServer-side Request Forgery (SSRF) is related to another type of vulnerability called Open Redirects in the sense that they both rely on untrusted input to reference other web-resources.\nStrategies for avoiding and/or fixing Server-Side Request Forgery include:\nDesign around it: Unless there is a reason why URL information must be passed, avoid the problem entirely by implementing an alternative design. Validation: When a URL value is received by the application, it must be white-list validated against the domain of possible legitimate values and rejected if it is not a member. Indirect References: In some cases, it may be possible to pass a (cryptographically strong) random value that represents the target URL and maintain a token: URL mapping on the server. Since URLs are never passed and the tokens are (practically) un-guessable, the vulnerability is eliminated. If URI is hard-coded, then the attacker cannot influence where the request is going, so it would look to be a false positive. However, although some scanning software is known for false positives, you need to be careful, as most scanning software are correct in their analysis. You need to check the whole source-to-sink trace that scanning software provides? If it is reporting only that one line as the source and sink, then yes it is a false positive.\nUseful links:\nhttps://www.owasp.org/index.php/Server_Side_Request_Forgery\n","date":"19 September 2019","externalUrl":null,"permalink":"/server-side-request-forgery-ssrf/","section":"Articles","summary":" Description “Server Side Request Forgery” (a.k.a. SSRF) is a class of web-application vulnerability in which an attacker can cause a website to access unintended server-side resources, including the unauthorized reading, writing, or execution of server resources.\nWeb-applications designed to pass URLs (references to server accessible content) or portions thereof, from the client browser to the application server using HTTP request parameters or HTTP request headers, are at risk for Server Side Request Forgery exploitation unless they protect against it.\nServer-side Request Forgery (SSRF) is related to another type of vulnerability called Open Redirects in the sense that they both rely on untrusted input to reference other web-resources.\nStrategies for avoiding and/or fixing Server-Side Request Forgery include:\nDesign around it: Unless there is a reason why URL information must be passed, avoid the problem entirely by implementing an alternative design. Validation: When a URL value is received by the application, it must be white-list validated against the domain of possible legitimate values and rejected if it is not a member. Indirect References: In some cases, it may be possible to pass a (cryptographically strong) random value that represents the target URL and maintain a token: URL mapping on the server. Since URLs are never passed and the tokens are (practically) un-guessable, the vulnerability is eliminated. If URI is hard-coded, then the attacker cannot influence where the request is going, so it would look to be a false positive. However, although some scanning software is known for false positives, you need to be careful, as most scanning software are correct in their analysis. You need to check the whole source-to-sink trace that scanning software provides? If it is reporting only that one line as the source and sink, then yes it is a false positive.\nUseful links:\nhttps://www.owasp.org/index.php/Server_Side_Request_Forgery\n","title":"Server-Side Request Forgery (SSRF)","type":"articles"},{"content":"","date":"19 September 2019","externalUrl":null,"permalink":"/categories/html/","section":"Categories","summary":"","title":"HTML","type":"categories"},{"content":" Description A function call contains an HTTP response splitting flaw. Writing untrusted input into an HTTP header allows an attacker to manipulate the HTTP response rendered by the browser, leading to cache poisoning and cross-site scripting attacks.\nRecommendations Remove unexpected carriage returns and line feeds from untrusted data used to construct an HTTP response. Always validate untrusted input to ensure that it conforms to the expected format, using centralized data validation routines when possible.\nA simple string extension can resolve this issue:\npublic static string CRLFRemoval(this string token) {\nreturn token.Replace(\u0026quot;%0d\u0026quot;, string.Empty, StringComparison.InvariantCultureIgnoreCase)\n.Replace(\u0026quot;%0D\u0026quot;, string.Empty, StringComparison.InvariantCultureIgnoreCase)\n.Replace(\u0026quot;\\r\u0026quot;, string.Empty)\n.Replace(\u0026quot;\\n\u0026quot;, string.Empty)\n.Replace(\u0026quot;%0a\u0026quot;, string.Empty, StringComparison.InvariantCultureIgnoreCase)\n.Replace(\u0026quot;%0A\u0026quot;, string.Empty, StringComparison.InvariantCultureIgnoreCase);\n}\nLinks for reference:\nhttps://en.wikipedia.org/wiki/HTTP_response_splitting\nhttps://securiteam.com/securityreviews/5WP0E2KFGK\nhttps://www.owasp.org/index.php?title=Testing_for_HTTP_Splitting/Smuggling_(OTG-INPVAL-017)\n","date":"19 September 2019","externalUrl":null,"permalink":"/improper-neutralization-of-crlf-sequences-in-http-headers/","section":"Articles","summary":" Description A function call contains an HTTP response splitting flaw. Writing untrusted input into an HTTP header allows an attacker to manipulate the HTTP response rendered by the browser, leading to cache poisoning and cross-site scripting attacks.\nRecommendations Remove unexpected carriage returns and line feeds from untrusted data used to construct an HTTP response. Always validate untrusted input to ensure that it conforms to the expected format, using centralized data validation routines when possible.\nA simple string extension can resolve this issue:\npublic static string CRLFRemoval(this string token) {\nreturn token.Replace(\"%0d\", string.Empty, StringComparison.InvariantCultureIgnoreCase)\n.Replace(\"%0D\", string.Empty, StringComparison.InvariantCultureIgnoreCase)\n.Replace(\"\\r\", string.Empty)\n.Replace(\"\\n\", string.Empty)\n.Replace(\"%0a\", string.Empty, StringComparison.InvariantCultureIgnoreCase)\n.Replace(\"%0A\", string.Empty, StringComparison.InvariantCultureIgnoreCase);\n}\nLinks for reference:\nhttps://en.wikipedia.org/wiki/HTTP_response_splitting\nhttps://securiteam.com/securityreviews/5WP0E2KFGK\nhttps://www.owasp.org/index.php?title=Testing_for_HTTP_Splitting/Smuggling_(OTG-INPVAL-017)\n","title":"Improper Neutralization of CRLF Sequences in HTTP Headers","type":"articles"},{"content":"The implementation of generic repositories and Unit Of Work are complex tasks in MongoDB. The lack of mechanisms in the component hinders its adoption. See how to implement this article.\nUnit of Work Unit Of Work is a standard used to group one or more operations (usually database operations) into a single transaction or “unit of work”, so that all operations are approved or disapproved as one.\nRepository Pattern Repositories are classes or components that encapsulate the logic needed to access the database (repository). Centralize common data access functionality. Providing better maintenance and decoupling of the infrastructure from the domain layer.\nBenefits Code decoupling and re-usability.\nCreating a Repository Pattern with Generics in .NET allows you to implement CRUD operations with very little effort and code.\nTogether with the Unit Of Work, in case of any error in the flow of the operation, it avoids any modification in the bank.\nAnd this control is in the application rather than opening transactions in the bank and avoiding locks in the tables.\nWhere’s MongoDB? MongoDB does not have transaction control in the .NET driver. With MongoDB’s popularity increasing, more and more systems are being implemented with it. Soon this article will address how to implement one.\nImplementation For this implementation, you will need the MongoDB.Driver and ServiceStack.Core components.\nTo install the components, open the Package Manager (View\u0026gt; Other Windows\u0026gt; Package Manager Console) and enter the commands:\nInstall-Package ServiceStack.Core Install-Package MongoDB.Driver Generic Repository To implement the Repository Pattern, an abstract generics class will be used with CRUD operations.\nInterface public interface IRepository\u0026lt;TEntity\u0026gt; : IDisposable where TEntity : class { Task Add(TEntity obj); Task\u0026lt;TEntity\u0026gt; GetById(Guid id); Task\u0026lt;IEnumerable\u0026lt;TEntity\u0026gt;\u0026gt; GetAll(); Task Update(TEntity obj); Task Remove(Guid id); } Implementation public abstract class BaseRepository \u0026lt; TEntity \u0026gt;: IRepository \u0026lt; TEntity \u0026gt; where TEntity : class { protected readonly IMongoContext _context ; protected readonly IMongoCollection \u0026lt; TEntity \u0026gt; DbSet ; protected BaseRepository ( IMongoContext context ) { _context = context ; DbSet = _context . GetCollection \u0026lt; TEntity \u0026gt; ( typeof ( TEntity ). Name ); }\npublic virtual Task Add ( TEntity obj ) { return _context . AddCommand ( async () =\u0026gt; await DbSet . InsertOneAsync ( obj )); }\npublic virtual async Task \u0026lt; TEntity \u0026gt; GetById ( Guid id ) { var data = await DbSet . FindAsync ( Builders \u0026lt; TEntity \u0026gt;. Filter . Eq ( \u0026quot; _id \u0026quot; , id )); return data . FirstOrDefault (); }\npublic virtual async Task \u0026lt; IEnumerable \u0026lt; TEntity \u0026gt;\u0026gt; GetAll () { var all = await DbSet . FindAsync ( Builders \u0026lt; TEntity \u0026gt;. Filter . Empty ); return all . ToList (); }\npublic virtual Task Update ( TEntity obj ) { return _context . AddCommand ( async () =\u0026gt; { await DbSet . ReplaceOneAsync ( Builders \u0026lt; TEntity \u0026gt;. Filter . Eq ( \u0026quot; _id \u0026quot; , obj . GetId ()) obj ); }); }\npublic virtual Task Remove ( Guid id ) =\u0026gt; _context . AddCommand (() =\u0026gt; DbSet . DeleteOneAsync ( Builders \u0026lt; TEntity \u0026gt;. Filter . Eq ( \u0026quot; _id \u0026quot; , id )));\npublic void Dispose () { GC . SuppressFinalize ( this ); } }\nEach Model will have its own implementation. For example a Product class:\npublic interface IProductRepository : IRepository \u0026lt; Product \u0026gt; { } // Implementation public class ProductRepository : BaseRepository \u0026lt; Product \u0026gt;, IProductRepository { public ProductRepository ( IMongoContext context ): base ( context ) { } }\nUnit of Work Unit Of Work will be responsible for performing the transactions that the Repositories have made. For this work to be done, a Mongo Context must be created. This Context will be the connection between the Repository and UoW.\nMongo Context public class MongoContext : IMongoContext { private IMongoDatabase Database { get; set; } private readonly List\u0026lt;Func\u0026lt;Task\u0026gt;\u0026gt; _commands; public MongoContext(IConfiguration configuration) { // Set Guid to CSharp style (with dash -) BsonDefaults.GuidRepresentation = GuidRepresentation.CSharpLegacy; // Every command will be stored and it\u0026rsquo;ll be processed at SaveChanges _commands = new List\u0026lt;Func\u0026lt;Task\u0026gt;\u0026gt;();\nRegisterConventions();\n// Configure mongo (You can inject the config, just to simplify) var mongoClient = new MongoClient(configuration.GetSection(\u0026ldquo;MongoSettings\u0026rdquo;).GetSection(\u0026ldquo;Connection\u0026rdquo;).Value);\nDatabase = mongoClient.GetDatabase(configuration.GetSection(\u0026ldquo;MongoSettings\u0026rdquo;).GetSection(\u0026ldquo;DatabaseName\u0026rdquo;).Value); }\nprivate void RegisterConventions() { var pack = new ConventionPack { new IgnoreExtraElementsConvention(true), new IgnoreIfDefaultConvention(true) }; ConventionRegistry.Register(\u0026ldquo;My Solution Conventions\u0026rdquo;, pack, t =\u0026gt; true); }\npublic int SaveChanges() { var qtd = _commands.Count; foreach (var command in _commands) { command(); }\n_commands.Clear(); return qtd; }\npublic IMongoCollection\u0026lt;T\u0026gt; GetCollection\u0026lt;T\u0026gt;(string name) { return Database.GetCollection\u0026lt;T\u0026gt;(name); }\npublic void Dispose() { GC.SuppressFinalize(this); }\npublic Task AddCommand(Func\u0026lt;Task\u0026gt; func) { _commands.Add(func); return Task.CompletedTask; } }\nUoW implementation public interface IUnitOfWork : IDisposable { bool Commit (); } public class UnitOfWork : IUnitOfWork { private readonly IMongoContext _context ;\npublic UnitOfWork ( IMongoContext context ) { _context = context ; }\npublic bool Commit () { return _context . SaveChanges () \u0026gt; 0 ; }\npublic void Dispose () { _context . Dispose (); } }\nConfiguring Startup.cs To finalize the configuration, open the project’s Startup.cs and add the DI settings.\npublic void ConfigureServices ( IServiceCollection services ) { services . AddMvc (). SetCompatibilityVersion ( CompatibilityVersion . Version_2_2 ); services . AddScoped \u0026lt; IMongoContext , MongoContext \u0026gt; (); services . AddScoped \u0026lt; IUnitOfWork , UnitOfWork \u0026gt; (); services . AddScoped \u0026lt; IProductRepository , ProductRepository \u0026gt; (); } The project code is available on Bruno Brito’s GitHub\nI have then the post by Bruno Brito and translated it in to English, mainly because the article was simple and what I was working on\n","date":"11 April 2019","externalUrl":null,"permalink":"/asp-net-core-mongodb-repository-pattern-unit-of-work/","section":"Articles","summary":"The implementation of generic repositories and Unit Of Work are complex tasks in MongoDB. The lack of mechanisms in the component hinders its adoption. See how to implement this article.\nUnit of Work Unit Of Work is a standard used to group one or more operations (usually database operations) into a single transaction or “unit of work”, so that all operations are approved or disapproved as one.\n","title":"ASP.NET Core – MongoDB Repository Pattern \u0026 Unit Of Work","type":"articles"},{"content":"","date":"11 April 2019","externalUrl":null,"permalink":"/categories/irepository/","section":"Categories","summary":"","title":"IRepository","type":"categories"},{"content":"","date":"11 April 2019","externalUrl":null,"permalink":"/categories/mongodb/","section":"Categories","summary":"","title":"MongoDB","type":"categories"},{"content":"","date":"11 April 2019","externalUrl":null,"permalink":"/categories/repository-pattern/","section":"Categories","summary":"","title":"Repository Pattern","type":"categories"},{"content":"","date":"11 April 2019","externalUrl":null,"permalink":"/categories/alm/","section":"Categories","summary":"","title":"ALM","type":"categories"},{"content":"When is something done? What does DONE mean?\nIn the teams of software development, here is a definition that can apply to this process:\nDefinition of Done The meaning of done is an agreed upon list of the activities necessary to get product increment to a production ready state.\nDevelopment completed Passed code and peer review (Pull Request in BitBucket) All Technical documentation is created and stored in the source repository Sanity check to confirm technical debt is identified and logged in the tech debt register identified and logged/recorded? Testing has been completed and no issues logged against acceptance tests. Deployed and tested against the acceptance criteria in a valid environment All non-functional requirements have been met Regression test packs updated Update tickets, including documentation, annotation and outcomes Product owner/Business Designer has signed off the work. Release to Production These are the necessary steps that apply to the development process where every you work\n","date":"11 April 2019","externalUrl":null,"permalink":"/done-when-done-means-done/","section":"Articles","summary":"When is something done? What does DONE mean?\nIn the teams of software development, here is a definition that can apply to this process:\nDefinition of Done The meaning of done is an agreed upon list of the activities necessary to get product increment to a production ready state.\n","title":"DONE – when done means DONE","type":"articles"},{"content":"","date":"20 February 2019","externalUrl":null,"permalink":"/categories/azure-sql-server/","section":"Categories","summary":"","title":"Azure SQL Server","type":"categories"},{"content":"What Is Multi-Tenancy? “Software Multitenancy refers to a software architecture in which a single instance of a software runs on a server and serves multiple tenants. A tenant is a group of users who share common access with specific privileges to the software instance. With a multitenant architecture, a software application is designed to provide every tenant a dedicated share of the instance including its data, configuration, user management, tenant individual functionality and non-functional properties. Multitenancy contrasts with multi-instance architectures, where separate software instances operate on behalf of different tenants” (Wikipedia)\nIn short, multi-tenancy is a technique that is used to create SaaS (Software-as-a-Service) applications.\nDatabase \u0026amp; Deployment Architectures There are some different multi-tenant database \u0026amp; deployment approaches:\nMultiple Deployment – Multiple Database This is not multi-tenancy actually, but if we run one instance of the application for each customer (tenant) with a separated database, we can serve multiple tenants on a single server. We just have to make sure that multiple instances of the application don’t conflict with each other on the same server environment.\nThis can also be possible for an existing application which is not designed as multi-tenant. It’s easier to create such an application since the application is not aware of multitenancy. There are, however, setup, utilization and maintenance problems in this approach.\nSingle Deployment – Multiple Database ln this approach, we run a single instance of the application on a server. We have a master (host) database to store tenant metadata (like tenant name and subdomain) and a separate database for each tenant. Once we identify the current tenant (for example; from a subdomain or from a user login form), then we can switch to that tenant’s database to perform operations.\nIn this approach, the application should be designed as multi-tenant at some level, but most of the application can remain independent from it.\nWe create and maintain a separate database for each tenant, this includes database migrations. If we have many customers with dedicated databases, it may take a long time to migrate the database schema during an application update. Since we have a separated database for each tenant, we can back up its database separately from other tenants. We can also move the tenant database to a stronger server if that tenant needs it.\nSingle Deployment – Single Database This is the most ideal multi-tenancy architecture: We only deploy a single instance of the application with a single database on to a single server. We have a TenantId (or similar) field in each table (for an RDBMS) which is used to isolate a tenant’s data from others.\nThis type of application is easy to set up and maintain, but harder to create. This is because we must prevent a Tenant from reading or writing to other tenant data. We may add a TenantId filter for each database read (select) operation. We may also check it every time we write, to see if this entity is related to the current tenant. This is tedious and error-prone. However, ASP.NET Boilerplate helps us here by using automatic data filtering.\nThis approach may have performance problems if we have many tenants with large data sets. We can use table partitioning or other database features to overcome this problem.\nSingle Deployment – Hybrid Databases We may want to store tenants in a single database normally but may want to create a separate database for desired tenants. For example, we can store tenants with big data in their own databases but store all other tenants in a single database.\nMultiple Deployment – Single/Multiple/Hybrid Database Finally, we may want to deploy our application to more than one server (like web farms) for better application performance, high availability, and/or scalability. This is independent of the database approach.\nMulti-Tenancy in ASP.NET Boilerplate ASP.NET Boilerplate can work with all the scenarios described above.\nEnabling Multi-Tenancy Multi-tenancy is disabled by default for Framework level. We can enable it in PreInitialize method of our module as shown below:\nConfiguration.MultiTenancy.IsEnabled = true; Note: Multi-tenancy is enabled in both ASP.NET Core and ASP.NET MVC 5.x startup templates.\nIgnore Feature Check For Host Users There is another configuration to ignore feature check for host users. We can enable it in PreInitialize method of our module as shown below:\nConfiguration.MultiTenancy.IgnoreFeatureCheckForHostUsers = true; Note: IgnoreFeatureCheckForHostUsers default value is false;\nHost vs Tenant We define two terms used in a multi-tenant system:\nTenant: A customer which has its own users, roles, permissions, settings… and uses the application completely isolated from other tenants. A multi-tenant application will have one or more tenants. If this is a CRM application, different tenants also have their own accounts, contacts, products and orders. So when we say a ‘tenant user‘, we mean a user-owned by a tenant. Host: The Host is a singleton (there is a single host). The Host is responsible for creating and managing tenants. A ‘host user‘ is at a higher level and independent from all tenants and can control them. Session ASP.NET Boilerplate defines the IAbpSession interface to obtain the current user and tenant ids. This interface is used in multi-tenancy to get the current tenant’s id by default. Thus, it can filter data based on the current tenant’s id. Here are the rules:\nIf both the UserId and the TenantId is null, then the current user is not logged in to the system. We can not know if it’s a host user or tenant user. In this case, the user can not access authorized content. If the UserId is not null and the TenantId is null, then we know that the current user is a host user. If the UserId is not null and the TenantId is not null, we know that the current user is a tenant user. If the UserId is null but the TenantId is not null, that means we know the current tenant, but the current request is not authorized (user did not login). See the next section to understand how the current tenant is determined. See the session documentation for more information.\nDetermining Current Tenant Since all tenant users use the same application, we should have a way of distinguishing the tenant of the current request. The default session implementation (ClaimsAbpSession) uses different approaches to find the tenant related to the current request in this given order:\nIf the user is logged in, it gets the TenantId from current claims. Claim name is http://www.aspnetboilerplate.com/identity/claims/tenantId and should contain an integer value. If it’s not found in claims then the user is assumed to be a host user. If the user has not logged in, then it tries to resolve the TenantId from the tenant resolve contributors. There are 3 pre-defined tenant contributors and are run in a given order (first successful resolver ‘wins’): DomainTenantResolveContributor: Tries to resolve tenancy name from an url, generally from a domain or subdomain. You can configure the domain format in the PreInitialize method of your module (like Configuration.Modules.AbpWebCommon().MultiTenancy.DomainFormat = “{0}.mydomain.com”;). If the domain format is “{0}.mydomain.com” and the current host of the request is acme.mydomain.com, then the tenancy name is resolved as “acme”. The next step is to query ITenantStore to find the TenantId by the given tenancy name. If a tenant is found, then it’s resolved as the current TenantId. HttpHeaderTenantResolveContributor: Tries to resolve TenantId from an “Abp.TenantId” header value, if present. This is a constant defined in Abp.MultiTenancy.MultiTenancyConsts.TenantIdResolveKey. HttpCookieTenantResolveContributor: Tries to resolve the TenantId from an “Abp.TenantId” cookie value, if present. This uses the same constant explained above. By default, ASP.NET Boilerplate uses “Abp.TenantId” to find TenantId from Cookie or Request Headers. You can change it using multi-tenancy configuration:\nConfiguration.MultiTenancy.TenantIdResolveKey = \"Abp-TenantId\"; You also need to configure it on the client side:\nabp.multiTenancy.tenantIdCookieName = 'Abp-TenantId'; If none of these attempts can resolve a TenantId, then the current requester is considered to be the host. Tenant resolvers are extensible. You can add resolvers to the Configuration.MultiTenancy.Resolvers collection, or remove an existing resolver.\nOne last thing on resolvers: The resolved tenant id is cached during the same request for performance reasons. Resolvers are executed once in a request, and only if the current user has not already logged in.\nTenant Store The DomainTenantResolveContributor uses ITenantStore to find the tenant id by tenancy name. The default implementation of ITenantStore is NullTenantStore which does not contain any tenant and returns null for queries. You can implement and replace it to query tenants from any data source. Module Zero properly implements it by getting it from its tenant manager. So if you are using Module Zero, you don’t need to worry about the tenant store.\nData Filters For the multi-tenant single database approach, we must add a TenantId filter to only get the current tenant’s entities when retrieving entities from the database. ASP.NET Boilerplate automatically does it when you implement one of the two interfaces for your entity: IMustHaveTenant and IMayHaveTenant.\nIMustHaveTenant Interface This interface is used to distinguish the entities of different tenants by defining a TenantId property. An example entity that implements IMustHaveTenant:\npublic class Product : Entity, IMustHaveTenant { public int TenantId { get; set; } public string Name { get; set; } //...other properties }\nThis way, ASP.NET Boilerplate knows that this is a tenant-specific entity and automatically isolates the entities of a tenant from other tenants.\nIMayHaveTenant interface We may need to share an entity type between host and tenants. As such, an entity may be owned by a tenant or the host. The IMayHaveTenant interface also defines TenantId (similar to IMustHaveTenant), but it is nullable in this case. An example entity that implements IMayHaveTenant:\npublic class Role : Entity, IMayHaveTenant { public int? TenantId { get; set; } public string RoleName { get; set; } //...other properties }\nWe may use the same Role class to store Host roles and Tenant roles. In this case, the TenantId property says if this is a host entity or tenant entity. A null value means this is a host entity, a non-null value means this entity is owned by a tenant where the Id is the TenantId.\nAdditional Notes IMayHaveTenant is not as common as IMustHaveTenant. For example, a Product class can not be IMayHaveTenant since a Product is related to the actual application functionality, and not related to managing tenants. So use the IMayHaveTenant interface carefully since it’s harder to maintain code-shared by host and tenants.\nWhen you define an entity type as IMustHaveTenant or IMayHaveTenant, always set the TenantId when you create a new entity (While ASP.NET Boilerplate tries to set it from current TenantId, it may not be possible in some cases, especially for IMayHaveTenant entities). Most of the time, this will be the only point you deal with the TenantId properties. You don’t need to explicitly write the TenantId filter in Where conditions while writing LINQ since it is automatically filtered.\nSwitching Between Host and Tenants While working on a multi-tenant application database, we can get the current tenant. By default, it’s obtained from the IAbpSession (as described before). We can change this behaviour and switch to another tenant’s database. Example:\npublic class ProductService : ITransientDependency { private readonly IRepository\u0026amp;lt;Product\u0026gt; _productRepository; private readonly IUnitOfWorkManager _unitOfWorkManager; public ProductService(IRepository\u0026amp;amp;lt;Product\u0026amp;gt; productRepository, IUnitOfWorkManager unitOfWorkManager) { _productRepository = productRepository; _unitOfWorkManager = unitOfWorkManager; } [UnitOfWork] public virtual List\u0026amp;amp;lt;Product\u0026amp;gt; GetProducts(int tenantId) { using (_unitOfWorkManager.Current.SetTenantId(tenantId)) { return _productRepository.GetAllList(); } } }\nSetTenantId ensures that we are working on a given tenant’s data, independent from the database architecture:\nIf the given tenant has a dedicated database, it switches to that database and gets products from it. If the given tenant does not have a dedicated database (the single database approach, for example), it adds the automatic TenantId filter to query only that tenant’s products. If we don’t use SetTenantId, it gets the tenantId from the session. There are some guidelines and best practices here:\nUse SetTenantId(null) to switch to the host. Use SetTenantId within a using block (as in the example) if there is not a special case. This way, it automatically restores the tenantId at the end of the using block and the code calling the GetProducts method works as before. You can use SetTenantId in nested blocks if it’s needed. Since _unitOfWorkManager.Current is only available in a unit of work, be sure that your code runs in a UOW. Orginal article\n","date":"20 February 2019","externalUrl":null,"permalink":"/multi-tenancy/","section":"Articles","summary":"What Is Multi-Tenancy? “Software Multitenancy refers to a software architecture in which a single instance of a software runs on a server and serves multiple tenants. A tenant is a group of users who share common access with specific privileges to the software instance. With a multitenant architecture, a software application is designed to provide every tenant a dedicated share of the instance including its data, configuration, user management, tenant individual functionality and non-functional properties. Multitenancy contrasts with multi-instance architectures, where separate software instances operate on behalf of different tenants” (Wikipedia)\n","title":"Multi-Tenancy","type":"articles"},{"content":"If you just want to export all the tables in a SQL database in to separate CSV files, then this is a quick and easy way of doing it.\nExecute below query which generates BCP commands\nSELECT ‘bcp ‘ + st.NAME + ‘ out c:\\Target\\’ + st.NAME + ‘.csv -c -r -d ‘ + DB_NAME() + ‘ -U user@??????.database.windows.net -S tcp:?????.database.windows.net -P ?????? FROM sys.tables st Paste the result set into text file. Make batch file and schedule it. (It can also be run in CMD manually) ","date":"16 January 2019","externalUrl":null,"permalink":"/how-to-export-all-tables-to-csv-by-one-export-job/","section":"Articles","summary":"If you just want to export all the tables in a SQL database in to separate CSV files, then this is a quick and easy way of doing it.\nExecute below query which generates BCP commands\nSELECT ‘bcp ‘ + st.NAME + ‘ out c:\\Target\\’ + st.NAME + ‘.csv -c -r -d ‘ + DB_NAME() + ‘ -U user@??????.database.windows.net -S tcp:?????.database.windows.net -P ?????? FROM sys.tables st Paste the result set into text file. Make batch file and schedule it. (It can also be run in CMD manually) ","title":"How to export all tables to csv by one export job","type":"articles"},{"content":"A nice short video showing how to debug a web service in Microsoft Azure\n","date":"28 November 2018","externalUrl":null,"permalink":"/how-to-configure-remote-debugging-for-web-apps-visual-studio-2017/","section":"Articles","summary":"A nice short video showing how to debug a web service in Microsoft Azure\n","title":"How to configure remote debugging for Web Apps \u0026 Visual Studio 2017","type":"articles"},{"content":"","date":"26 November 2018","externalUrl":null,"permalink":"/categories/git/","section":"Categories","summary":"","title":"Git","type":"categories"},{"content":"I have tried a number of Git GUI’s and the best by far has to the Source Tree\nhttps://www.sourcetreeapp.com/\nWhy? It’s just so easy to use and displays what you need when you need it.\n","date":"26 November 2018","externalUrl":null,"permalink":"/the-best-git-gui/","section":"Articles","summary":"I have tried a number of Git GUI’s and the best by far has to the Source Tree\nhttps://www.sourcetreeapp.com/\nWhy? It’s just so easy to use and displays what you need when you need it.\n","title":"The best GIT GUI","type":"articles"},{"content":"It is important that when writing RESTful API’s that the correct HTTP status code is returned, the best and only source of reference has to be: https://httpstatuses.com/\n1×× Informational 100 Continue 101 Switching Protocols 102 Processing 2×× Success 200 OK 201 Created 202 Accepted 203 Non-authoritative Information 204 No Content 205 Reset Content 206 Partial Content 207 Multi-Status 208 Already Reported 226 IM Used 3×× Redirection 300 Multiple Choices 301 Moved Permanently 302 Found 303 See Other 304 Not Modified 305 Use Proxy 307 Temporary Redirect 308 Permanent Redirect 4×× Client Error 400 Bad Request 401 Unauthorized 402 Payment Required 403 Forbidden 404 Not Found 405 Method Not Allowed 406 Not Acceptable 407 Proxy Authentication Required 408 Request Timeout 409 Conflict 410 Gone 411 Length Required 412 Precondition Failed 413 Payload Too Large 414 Request-URI Too Long 415 Unsupported Media Type 416 Requested Range Not Satisfiable 417 Expectation Failed 418 I’m a teapot 421 Misdirected Request 422 Unprocessable Entity 423 Locked 424 Failed Dependency 426 Upgrade Required 428 Precondition Required 429 Too Many Requests 431 Request Header Fields Too Large 444 Connection Closed Without Response 451 Unavailable For Legal Reasons 499 Client Closed Request 5×× Server Error 500 Internal Server Error 501 Not Implemented 502 Bad Gateway 503 Service Unavailable 504 Gateway Timeout 505 HTTP Version Not Supported 506 Variant Also Negotiates 507 Insufficient Storage 508 Loop Detected 510 Not Extended 511 Network Authentication Required 599 Network Connect Timeout Error ","date":"2 November 2018","externalUrl":null,"permalink":"/http-status-codes/","section":"Articles","summary":"It is important that when writing RESTful API’s that the correct HTTP status code is returned, the best and only source of reference has to be: https://httpstatuses.com/\n1×× Informational 100 Continue 101 Switching Protocols 102 Processing 2×× Success 200 OK 201 Created 202 Accepted 203 Non-authoritative Information 204 No Content 205 Reset Content 206 Partial Content 207 Multi-Status 208 Already Reported 226 IM Used 3×× Redirection 300 Multiple Choices 301 Moved Permanently 302 Found 303 See Other 304 Not Modified 305 Use Proxy 307 Temporary Redirect 308 Permanent Redirect 4×× Client Error 400 Bad Request 401 Unauthorized 402 Payment Required 403 Forbidden 404 Not Found 405 Method Not Allowed 406 Not Acceptable 407 Proxy Authentication Required 408 Request Timeout 409 Conflict 410 Gone 411 Length Required 412 Precondition Failed 413 Payload Too Large 414 Request-URI Too Long 415 Unsupported Media Type 416 Requested Range Not Satisfiable 417 Expectation Failed 418 I’m a teapot 421 Misdirected Request 422 Unprocessable Entity 423 Locked 424 Failed Dependency 426 Upgrade Required 428 Precondition Required 429 Too Many Requests 431 Request Header Fields Too Large 444 Connection Closed Without Response 451 Unavailable For Legal Reasons 499 Client Closed Request 5×× Server Error 500 Internal Server Error 501 Not Implemented 502 Bad Gateway 503 Service Unavailable 504 Gateway Timeout 505 HTTP Version Not Supported 506 Variant Also Negotiates 507 Insufficient Storage 508 Loop Detected 510 Not Extended 511 Network Authentication Required 599 Network Connect Timeout Error ","title":"HTTP Status Codes","type":"articles"},{"content":"","date":"17 October 2018","externalUrl":null,"permalink":"/categories/node.js/","section":"Categories","summary":"","title":"Node.js","type":"categories"},{"content":"","date":"17 October 2018","externalUrl":null,"permalink":"/categories/openapi/","section":"Categories","summary":"","title":"OpenAPI","type":"categories"},{"content":"You’ve been playing with Swagger and can now see the benefits, and you are planning to use a YAML file, now you would like to display it to the outside work, here is a short article explaining all that is required. This is based on you using Express within Node.js\nSwagger UI Express Adds middleware to your express app to serve the Swagger UI bound to your Swagger document. This acts as living documentation for your API hosted from within your app.\nSwagger version is pulled from npm module swagger-ui-dist. Please use a lock file or specify the version of swagger-ui-dist you want to ensure it is consistent across environments.\nUsage Install using npm:\n$ npm install swagger-ui-express Load swagger from yaml file To load your swagger specification yaml file you need to use a module able to convert yaml to json ; for instance yamljs.\nnpm install --save yamljs const express = require('express'); const app = express(); const swaggerUi = require('swagger-ui-express'); const YAML = require('yamljs'); const swaggerDocument = YAML.load('./swagger.yaml'); app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); A good example of Node.js using swagger can be found here: https://github.com/BryanAvery/Node.js_RESTfulAPI_Swagger For many, more options take a look here ","date":"17 October 2018","externalUrl":null,"permalink":"/swagger-ui-reading-yaml-file/","section":"Articles","summary":"You’ve been playing with Swagger and can now see the benefits, and you are planning to use a YAML file, now you would like to display it to the outside work, here is a short article explaining all that is required. This is based on you using Express within Node.js\n","title":"Swagger UI reading YAML file","type":"articles"},{"content":"Once you have installed swagger into your application, using this command:\nnpm install -g swagger To edit you active YAML file just type to following:\nswagger project edit ","date":"17 October 2018","externalUrl":null,"permalink":"/edit-your-swagger-yaml/","section":"Articles","summary":"Once you have installed swagger into your application, using this command:\nnpm install -g swagger To edit you active YAML file just type to following:\nswagger project edit","title":"Edit your Swagger YAML","type":"articles"},{"content":"What is Swagger? On the Swagger site we can find the definition of Swagger:\nSwagger is the world’s largest framework of API developer tools for the OpenAPI Specification(OAS), enabling development across the entire API lifecycle, from design and documentation, to test and deployment.\nSwagger contains a large ecosystem of tools from which we can single out a set of core tools:\nSwagger Editor Swagger Codegen Swagger UI Swagger Editor Swagger Editor is a tool that allows you to edit Swagger API specification inside your browser. While editing Swagger API specification, the tool will preview the documentation in real time. That way we can immediately see how documentation will look after applying the most recent changes. The editor is easy to use, has a clean user interface and has a lot of features to help you design and document RESTful APIs.\nSwagger Codegen Swagger code generator is a template-driven engine that allows you to generate interactive documentation, API clients and server stubs from Swagger definitions. List of supported languages is quite extensive.\nThere are the pros and cons of Swagger Codegen:\nPros: Generates server code, client code and documentation Allows quick changes of the API The code generator is open source Cons: Increase in project complexity by using additional tools and libraries Generates a lot of code that the user might not understand Swagger UI Swagger UI allows anyone to visualize a RESTful API. Visualization is automatically generated from the Swagger specification. So Swagger UI takes an existing JSON or YAML document and creates interactive documentation.\nUseful links https://swagger.io/tools/open-source/getting-started/\nhttps://swagger.io/resources/articles/documenting-apis-with-swagger/\nSpeed up your RESTful API development in Node.js with Swagger\nSwagger editor to allow you to edit your *.yaml files\nOpen API Specification\nhttps://scotch.io/tutorials/speed-up-your-restful-api-development-in-node-js-with-swagger\n","date":"17 October 2018","externalUrl":null,"permalink":"/swagger/","section":"Articles","summary":"What is Swagger? On the Swagger site we can find the definition of Swagger:\nSwagger is the world’s largest framework of API developer tools for the OpenAPI Specification(OAS), enabling development across the entire API lifecycle, from design and documentation, to test and deployment.\n","title":"Swagger","type":"articles"},{"content":"no need for me to explain what to do when Microsoft already has a very good article on debugging within Visual Studio Code\nhttps://code.visualstudio.com/docs/editor/debugging\n","date":"16 October 2018","externalUrl":null,"permalink":"/debugging-node-js-with-typescript/","section":"Articles","summary":"no need for me to explain what to do when Microsoft already has a very good article on debugging within Visual Studio Code\nhttps://code.visualstudio.com/docs/editor/debugging\n","title":"Debugging Node.js with Typescript","type":"articles"},{"content":"","date":"16 October 2018","externalUrl":null,"permalink":"/categories/visual-studio-code/","section":"Categories","summary":"","title":"Visual Studio Code","type":"categories"},{"content":"Before we start let’s just ask a few questions:\nWhy Typescript? There are two main goals of TypeScript:\nProvide an optional type system for JavaScript. Provide planned features from future JavaScript editions to current JavaScript engines The TypeScript type system You might be wondering “Why add types to JavaScript?“\nTypes have a proven ability to enhance code quality and understandability. Large teams (Google, Microsoft, Facebook) have continually arrived at this conclusion. Specifically:\nTypes increase your agility when doing refactoring. It’s better for the compiler to catch errors than to have things fail at runtime. Types are one of the best forms of documentation you can have. The function signature is a theorem and the function body is the proof. However, types have a way of being unnecessarily ceremonious. TypeScript is very particular about keeping the barrier to entry as low as possible.\nWhy node.js? Nodejs is fast, event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.\nGetting started First, you will need to install TypeScript into your node environment this is as easy as just running the following commands:\n$ npm init -y $ npm install -g typescript This will give your terminal global access to the TypeScript compiler, simply with using the tsc command.\nHere’s a simple example. Open up a code editor of your choice and create a simple file. But, give it an extension of .ts. we will name the file app.ts.\n// app.ts let x: number = 10; let y: number = 20; console.log(x + y); This is a trivial program, only defining two variables and logging their sum. We’re telling the TypeScript compiler to view these variables as numbers. Now when you jump back to the terminal you can compile a JavaScript file from the app.ts TypeScript file.\n$ tsc app.ts Running the command will create an app.js file in the same directory. Opening it up we can see it’s basic ES5 JavaScript.\n// app.js var x = 10; var y = 20; console.log(x + y); What if we assign a string value to a : number variable?\nlet x: number = 'Hello World!'; Change the value of x to 'Hello World!' and run the tsc app.ts command once again. You’ll get a nice error logged back to you.\napp.ts:1:5 - error TS2322: Type '\"Hello World!\"' is not assignable to type 'number'. 1 let x: number = \u0026lsquo;Hello World!\u0026rsquo;; ~\nWe really only want to run the compiled JavaSCript files in a production environment. For the development environment, we want to use a TypeScript execution environment for Node.js call ts-node\nInstalling it is as simple as installing TypeScript.\n$ npm install -g ts-node Simple enough. That’s all we need regarding the actual compilers and environments. We’re ready to write some real code.\nReal Coding Let’s get coding, but before we do let us install a few dependencies, express\n$ npm install --save express @types/express body-parser We’re installing express, the express data types for TypeScript, and of course body-parser.\nSetting up the compilation pipeline With the tsconfig.json file, we tell TypeScript what we want to compile and how, as well as where to place the compiled files.\n{ \"compilerOptions\": { \"module\": \"commonjs\", \"moduleResolution\": \"node\", \"pretty\": true, \"sourceMap\": true, \"target\": \"es6\", \"outDir\": \"./dist\", \"baseUrl\": \"./lib\" }, \"include\": [ \"lib/**/*.ts\" ], \"exclude\": [ \"node_modules\" ] } The outDir is set to ./dist, meaning it will create the dist directory and place the compiled files there.\nNow when you run the tsc command, it will read this file and compile everything just as you want. Let’s try it.\n$ tsc Running this you’ll see the new dist directory get created along with the app.js and server.js file. The .js files are now basic JavaScript files, written in ES6.\nTo make it easier to run, let’s add some scripts in the package.json. Use “npm init” to create package.json\nOpen up the package.json. You should have a \"scripts\" section. Add code so it looks like this:\n\"scripts\": { \"build\": \"tsc\", \"dev\": \"ts-node ./lib/server.ts\", \"start\": \"node ./dist/server.js\", \"prod\": \"npm run build \u0026amp;\u0026amp; npm start\" }, When you run npm run dev in the terminal you will spin up the app with the ts-node module, but if you run the npm run prod command you’ll first build the TypeScript files, and then run the compiled server.js file from the dist folder.\nThat’s enough for this article, next we will be looking at how to debug the node.js file that have been generated by TypeScript.\nThe source can be found here:\nhttps://github.com/BryanAvery/Typescript-with-Node.js\nThis article could not have been put together without the help of Adnan Rahic and his crash course on TypeScript with Node.js\n","date":"16 October 2018","externalUrl":null,"permalink":"/node-js-with-microsoft-typescript/","section":"Articles","summary":"Before we start let’s just ask a few questions:\nWhy Typescript? There are two main goals of TypeScript:\nProvide an optional type system for JavaScript. Provide planned features from future JavaScript editions to current JavaScript engines ","title":"Node.js with Microsoft TypeScript","type":"articles"},{"content":"","date":"16 October 2018","externalUrl":null,"permalink":"/categories/typescript/","section":"Categories","summary":"","title":"TypeScript","type":"categories"},{"content":"Here is a short article to provide a simple RESTful API using node.js.\nWhy use node.js? node.js is super fast and handles asynchronous without having to think about coding, it is javascript based and runs on such a small footprint that it is just the way things should be.\nI’ve taken the work already be done by @donyangetoh and adapted it to fit my needs.\nThis is an app demonstrating simple API implementation with Node.js, Express and MongoDb\nThe api uri precedes all API endpoints and the following endpoints are currently available\nGET /api/contacts POST /api/contacts GET /api/contacts/:id PUT /api/contacts/:id PATCH /api/contacts/:id DELETE /api/contacts/:id The source for this example can be found on GitHub:\nhttps://github.com/BryanAvery/Node.js_RESTfulAPI\n","date":"16 October 2018","externalUrl":null,"permalink":"/restfull-api-using-node-js-and-express-js/","section":"Articles","summary":"Here is a short article to provide a simple RESTful API using node.js.\nWhy use node.js? node.js is super fast and handles asynchronous without having to think about coding, it is javascript based and runs on such a small footprint that it is just the way things should be.\n","title":"RESTfull API using node.js and express.js","type":"articles"},{"content":"A clear rejection is always better than a fake promise, so when dealing with Promises in Node.JS consider the rejection aspect of the promise.\nIt is quite easy to handle, I prefer the Async method of handing promises, as it is much easier to read and understand.\nHere is an example of how to throw a reject and handle the error:\nfunction doSomething(message){ return new Promise(function (fulfill, reject){ setTimeout(() =\u0026gt; { reject(message + \" rejected\"); }, 2000); }); } (async function read() { try{ const data = await doSomething(\u0026lsquo;second promise\u0026rsquo;); console.log(data); } catch (error) { console.log(\u0026ldquo;error: \u0026quot; + error); } } )();\nconsole.log(\u0026ldquo;Will hit here first, then wait for two seconds\u0026rdquo;); The response should look something like this:\nWill hit here first, then wait for two seconds error: second promise rejected If you still wish to use the .then and .catch method of Promises then here syntax for that method:\ndoSomething('first promise') .then(data =\u0026gt; { console.log(data); }) .catch((err) =\u0026gt; { console.log(\"error: \" + err); }); For further reading take a look here\n","date":"15 October 2018","externalUrl":null,"permalink":"/how-to-handle-rejection-from-a-promise/","section":"Articles","summary":"A clear rejection is always better than a fake promise, so when dealing with Promises in Node.JS consider the rejection aspect of the promise.\nIt is quite easy to handle, I prefer the Async method of handing promises, as it is much easier to read and understand.\n","title":"How to handle rejection from a Promise","type":"articles"},{"content":"With Node.js you have the ability to make promises, but what is a promise?\nHere is a definition of a node.js promise\n‘A promise is an abstraction for asynchronous programming. It’s an object that proxies for the return value or the exception thrown by a function that has to do some asynchronous processing’\nThe core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states:\npending – The initial state of a promise. fulfilled – The state of a promise representing a successful operation. rejected – The state of a promise representing a failed operation. Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again).\nSo how do we create a Promise on Node.js?\nCreate a Promise We can create a promise in our Node JS program using the new constructor.\nvar myPromise = new Promise(function(fulfill, reject){ .... }) So myPromise is a Promise type object which allows us to use it for later.\nLet’s get down to writing a small sample application to show a promise fully working\nPromise in Action We will make a promise which will wait for 2 seconds and then update a message and display the message. Once the promise has been completed everything will finish.\nJust so we can see the order of tasks we will add a console.log at different points of the application.\nfunction doSomething(message){ return new Promise(function (fulfill){ setTimeout(() =\u0026gt; { fulfill(message + \u0026quot; fulfilled\u0026quot;); }, 2000); }); }\ndoSomething(\u0026lsquo;promise\u0026rsquo;) .then(data =\u0026gt; { console.log(data); });\nconsole.log(\u0026ldquo;Will hit here first, then wait for two seconds\u0026rdquo;);\nWhen you run this you should get the following results:\nWill hit here first, then wait for two seconds promise fulfilled Okay so far?\nAsync Consideration should be given to using Async/Await in place of .then .catch.\nThe Async pattern is a more preferable way to consume promises, which makes your promise consuming code more readable and easier, especially when dealing with loops and other complexities.\nfunction doSomething(message){ return new Promise(function (fulfill){ setTimeout(() =\u0026gt; { fulfill(message + \" fulfilled\"); }, 2000); }); } doSomething(\u0026lsquo;first promise\u0026rsquo;) .then(data =\u0026gt; { console.log(data); });\n(async function read() { const data = await doSomething(\u0026lsquo;second promise\u0026rsquo;); console.log(data); } )();\nconsole.log(\u0026ldquo;Will hit here first, then wait for two seconds\u0026rdquo;); Much nicer, and easier to read too.\n","date":"15 October 2018","externalUrl":null,"permalink":"/being-true-to-a-promise-in-node-js/","section":"Articles","summary":"With Node.js you have the ability to make promises, but what is a promise?\nHere is a definition of a node.js promise\n‘A promise is an abstraction for asynchronous programming. It’s an object that proxies for the return value or the exception thrown by a function that has to do some asynchronous processing’\n","title":"Being true to a Promise in Node.js","type":"articles"},{"content":"Node.js is a very powerful platform for building server-based applications.\nI have put together a list of very useful links which help with building and working with Node.js\nDownload link for installing Node.js, or use Homebrew\nhttps://nodejs.org/en/download/\nHomebrew installation\n/usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\" It is also important to add build essentials should you need to add any add-on in the future.\nsudo opt-get install -y build-essential NPM Documentation site is useful\nhttps://docs.npmjs.com/\nOne very useful section is the How to Prevent Permissions Errors\nMonitoring files for change and Auto restarting\nnpm i -g nodemon REPL – Read, Eval Print, Loop\nA useful and cross-platform editor is the Atom Editor\nIf you are running on a Windows machine then it is best to use a Virtual Machine, V8 or Chakra\nMongoDB The prefered choice of data store currently is MongoDB, not only is it fast easy and very scalable, but it suits the Async nature of node.js. You can download MongoDB here\nThe best module for Node.JS and MongoDB is Mongoose. Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in typecasting, validation, query building, business logic hooks and more, out of the box.\nMongoose quick-start guide\nMySql If you are old skool and using MySQL then it is worth downloading WorkBench to manage your databases\n","date":"15 October 2018","externalUrl":null,"permalink":"/useful-links-for-node-js/","section":"Articles","summary":"Node.js is a very powerful platform for building server-based applications.\nI have put together a list of very useful links which help with building and working with Node.js\nDownload link for installing Node.js, or use Homebrew\n","title":"Useful links for Node.js","type":"articles"},{"content":"MSMQ (Microsoft Message Queuing) is a message queue that is available by default as part of Windows. A reliable way of sending and receiving messages across computer systems, MSMQ provides a queue that’s scalable, thread-safe, simple, and convenient to use while at the same time providing you with the opportunity to persist the messages inside the Windows database.\nCreating a Queue You can turn on MSMQ in your system through the “Turn Windows features on or off” option from the control panel.\nOnce MSMQ has been installed in your system, creating a queue is simple. Just go to “My Computer”, right click and select Manage. In the “Computer Management” window you can create a new queue from the “Message Queuing” node. You can also create a queue programmatically.\nMSMQ in C# To work with MSMQ, you would need to include the System.Messaging namespace. To create a queue programmatically, you need to leverage the Create method of the MessageQueue class. The following code snippet illustrates this.\nMessageQueue.Create(@\".\\Private$\\IDG\");\nTo create a queue and send a message to it, you can use the following code snippet.\nMessageQueue.Create(@\".\\Private$\\IDG\"); messageQueue = new MessageQueue(@\".\\Private$\\IDG\");\nmessageQueue.Label = \"This is a test queue.\";\nmessageQueue.Send(\"This is a test message.\", \"IDG\");\nNow, suppose you would like to check if the queue exists and if it does, send a message to it. If the queue doesn’t exist, you may want to create a new one and then send it a message. This is exactly what the following code listing does for you.\nThe following code listing illustrates how you can process the messages stored in a message queue using C#.\nprivate static List\u0026lt;string\u0026gt; ReadQueue(string path)\n{\nList\u0026lt;string\u0026gt; lstMessages = new List\u0026lt;string\u0026gt;();\nusing (MessageQueue messageQueue = new MessageQueue(path))\n{\nSystem.Messaging.Message[] messages = messageQueue.GetAllMessages();\nforeach (System.Messaging.Message message in messages)\n{\nmessage.Formatter = new XmlMessageFormatter(\nnew String[] { \"System.String, mscorlib\" });\nstring msg = message.Body.ToString();\nlstMessages.Add(msg);\n}\n}\nreturn lstMessages;\n}\nNext, you can invoke the ReadQueue method to retrieve the messages stored in the message queue as shown in the code snippet below.\nstring path = @\".\\Private$\\IDG\";\nList\u0026lt;string\u0026gt; lstMessages = ReadQueue(path);\nYou can also store objects in the message queue. As an example, suppose you need to store a log message to the queue. The log message is stored in an instance of the LogMessage class that contains the necessary properties that pertain to the details of the log message. Here’s how the LogMessage class would look like — I’ve made it simple with just two properties only.\npublic class LogMessage\n{\npublic string MessageText { get; set; }\npublic DateTime MessageTime { get; set; }\n}\nYou should modify the LogMessage class to incorporate other necessary properties, i.e., message severity, etc. The following method illustrates how you can store an instance of the LogMessage class to the message queue.\nzzz\nThe following code snippet illustrates how you can create an instance of the LogMessage class, populate it with data and then invoke the SendMessage method to store the instance created in the message queue.\nLogMessage msg = new LogMessage()\n{\nMessageText = \"This is a test message.\",\nMessageTime = DateTime.Now\n};\nSendMessage(@\".\\Private$\\IDGLog\", msg);\nThe following code listing illustrates how you can read the LogMessage instance stored in the message queue.\nprivate static LogMessage ReceiveMessage(string queueName)\n{\nif (!MessageQueue.Exists(queueName))\nreturn null;\nMessageQueue messageQueue = new MessageQueue(queueName);\nLogMessage logMessage = null;\ntry\n{\nmessageQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(LogMessage) });\nlogMessage = (LogMessage)messageQueue.Receive().Body;\n}\ncatch { }\nfinally\n{\nmessageQueue.Close();\n}\nreturn logMessage;\n}\nGet started with Azure Queue storage using .NET\n","date":"7 October 2018","externalUrl":null,"permalink":"/microsoft-message-queuing/","section":"Articles","summary":"MSMQ (Microsoft Message Queuing) is a message queue that is available by default as part of Windows. A reliable way of sending and receiving messages across computer systems, MSMQ provides a queue that’s scalable, thread-safe, simple, and convenient to use while at the same time providing you with the opportunity to persist the messages inside the Windows database.\n","title":"Microsoft Message Queuing","type":"articles"},{"content":"There are a number of best practices when it comes to Async what I’ll try and cover here are the “guidelines” than actual rules. There are exceptions to each of these guidelines. The guidelines are summarised in the table below.\nSummary of Asynchronous Programming Guidelines\nName Description Exceptions Avoid async void Prefer async Task methods over async void methods Event handlers Async all the way Don’t mix blocking and async code Console main method Configure context Use ConfigureAwait(false) when you can Methods that require con­text Simple Asynchronous If you have a method that is Synchronis and you can make it Asynchronous how do you do that?\nWith all Async calls, you have to return something back, here is a simple example where you don’t need.\nTask.Run should be avoided on ASP.NET. This approach would remove all benefits from async/await and actually perform worse under load than just a synchronous call.\npublic async Task\u0026lt;string\u0026gt; DeleteMessage() { await Task.Run(() =\u0026gt; DeleteMessages()); return string.Empty; } If you do need to return something then it is just as easy\npublic async Task\u0026lt;string\u0026gt; GetFromQueue() { var message = await Task.Run(() =\u0026gt; GetMessage()); return message.Body.ToString(); } https://msdn.microsoft.com/en-us/magazine/jj991977.aspx\n","date":"4 September 2018","externalUrl":null,"permalink":"/how-to-async/","section":"Articles","summary":"There are a number of best practices when it comes to Async what I’ll try and cover here are the “guidelines” than actual rules. There are exceptions to each of these guidelines. The guidelines are summarised in the table below.\nSummary of Asynchronous Programming Guidelines\n","title":"How to Async","type":"articles"},{"content":"The problem? How can application A, handle events sent by an application B, and how to implements those events in B? Knowing that B has no idea of the existence of A.\nThe MemoryMapped way The following example shows how it would work, with the restriction that both applications are using the same memory space. In real code, the producer() method would be in a different application from the consumer() method, but this serves to illustrate an implementation:\nusing System; using System.IO; using System.IO.MemoryMappedFiles; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { void run() { Task.Run(() =\u0026gt; consumer()); Task.Run(() =\u0026gt; producer());\n\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;Console\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;WriteLine\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;Press \u0026amp;lt;ENTER\u0026amp;gt; to stop.\u0026quot;\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;);\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;Console\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;ReadLine\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;();\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;}\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;static\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;void\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; producer\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;()\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;{\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; using \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;var\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; mmf \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;MemoryMappedFile\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;CreateOrOpen\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;MyMapName\u0026quot;\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;,\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;lit\u0026quot;\u0026gt;1024\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;))\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; using \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;var\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; view \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; mmf\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;CreateViewStream\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;())\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;{\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;var\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; writer \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;new\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;BinaryWriter\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt;view\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;);\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;var\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; signal \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;new\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;EventWaitHandle\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;false\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;,\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;EventResetMode\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;AutoReset\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;,\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;MyEventName\u0026quot;\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;);\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;var\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; mutex \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;new\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;Mutex\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;false\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;,\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;MyMutex\u0026quot;\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;);\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;for\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;int\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; i \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;lit\u0026quot;\u0026gt;0\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;;\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; i \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;\u0026amp;lt;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;lit\u0026quot;\u0026gt;100\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;++\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt;i\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;)\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;{\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;string\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; message \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;Message #\u0026quot;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;+\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; i\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;;\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; mutex\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;WaitOne\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;();\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; writer\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;BaseStream\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;Position\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;lit\u0026quot;\u0026gt;0\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;;\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; writer\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;Write\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt;message\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;);\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; signal\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;Set\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;();\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; mutex\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;ReleaseMutex\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;();\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;Thread\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;Sleep\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;lit\u0026quot;\u0026gt;1000\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;);\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;}\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;}\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;}\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;static\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;void\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; consumer\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;()\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;{\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; using \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;var\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; mmf \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;MemoryMappedFile\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;CreateOrOpen\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;MyMapName\u0026quot;\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;,\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;lit\u0026quot;\u0026gt;1024\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;))\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; using \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;var\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; view \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; mmf\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;CreateViewStream\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;())\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;{\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;var\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; reader \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;new\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;BinaryReader\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt;view\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;);\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;var\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; signal \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;new\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;EventWaitHandle\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;false\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;,\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;EventResetMode\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;AutoReset\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;,\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;MyEventName\u0026quot;\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;);\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;var\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; mutex \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;new\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;Mutex\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;false\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;,\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;MyMutex\u0026quot;\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;);\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;while\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;true\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;)\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;{\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; signal\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;WaitOne\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;();\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; mutex\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;WaitOne\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;();\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; reader\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;BaseStream\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;Position\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;lit\u0026quot;\u0026gt;0\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;var\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; message \u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;=\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; reader\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;ReadString\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;();\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;Console\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;WriteLine\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;(\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;Received message: \u0026quot;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;+\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; message\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;);\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt; mutex\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;.\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;ReleaseMutex\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;();\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;}\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;}\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;}\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;static\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;void\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;Main\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;()\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;{\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwd\u0026quot;\u0026gt;new\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;typ\u0026quot;\u0026gt;Program\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;().\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pln\u0026quot;\u0026gt;run\u0026lt;/span\u0026gt;\u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;();\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;}\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;pun\u0026quot;\u0026gt;}\u0026lt;/span\u0026gt; }\nIMPORTANT: This implementation does not use a queue, so it is possible for the consumer to miss messages if it does not process them before a new message arrives.\nIf you do not want to miss any messages, you would have to use some queuing implementation instead, for example, MSMQ.\nHere is a sample application – EventsBetweenApplications\noriginal article ","date":"24 August 2018","externalUrl":null,"permalink":"/how-to-handle-events-between-applications/","section":"Articles","summary":"The problem? How can application A, handle events sent by an application B, and how to implements those events in B? Knowing that B has no idea of the existence of A.\nThe MemoryMapped way The following example shows how it would work, with the restriction that both applications are using the same memory space. In real code, the producer() method would be in a different application from the consumer() method, but this serves to illustrate an implementation:\n","title":"How to handle Events between Applications","type":"articles"},{"content":"Procedure \u0026amp; Rules An important element of Scrum is to estimate the complexity of features in the product backlog. For the estimation process, we use a simplified Fibonacci sequence: 0, 1, 2, 3, 5, 8, 13, 20, 40, 100.\nThe numbers do not indicate the amount of work in days but a relative variable known as story points. This reflects the complexity of a feature, in other words, the intellectual outlay’ involved in its implementation.\nEach person involved in the implementation of the product is given a deck of cards. Once the product owner has presented a feature and all questions have been answered, the estimation process can begin:\nIndividually and without discussion, each person assesses how, complex the feature is and selects a card, which they lay face down in front of them. Once everyone has laid down a card, the cards are turned over. If there are differences of opinion, the Scrum Master initiates a discussion. This is done by asking the two people with the highest and lowest numbers to discuss their estimates. After these views have been heard, either the development team agrees on a number or a second round of discussion takes place. The outcome of the estimates is especially interesting for the product owner. Using this and the velocity of the team, the product owner is able to carry out release planning for all features.\nExplanation of pictures 0 – Sleep. We could do this task in our sleep.\n1 – Child’s play. We do need to leave the comfort of our beds, but not much more is required.\n2 – Peanuts. It’s not for kids, but no real challenge for experienced developers.\n3 – Rockets. A task with a certain amount of challenge that lets us show what we can do. But not rocket science.\n5 – High jump. The bar has definitely been raised. But with thorough preparation and planning, it’s still a manageable task.\n8 – Thermometer. Tasks like this gradually make even experienced developers break into a sweat.\n13 – Fire. Others have already burned their fingers on projects like this. Approach with caution!\n20 – Bullfight. This task is a beast that can only be overcome with courage and determination. Let’s grab it by the horns – ole!\n40 – Mammoth. Huge and seemingly unconquer­able, this project looms above us. But if Stone Age hunters could do it, so can courageous developers!\n100 – Iceberg. What appears serene and beautiful from a distance turns out on closer inspection to be a deadly hazard. So slow down and proceed with extreme caution!\nThe impossible animal. It’s a fascinating idea. Maybe we can find a science fiction writer who will put it in their next novel?\n? – Train of thought. Pardon? I lost my train of thought\nThis list comes from Ulassa, a reliable source for Agile processes.\n","date":"21 August 2018","externalUrl":null,"permalink":"/story-pointing/","section":"Articles","summary":"Procedure \u0026 Rules An important element of Scrum is to estimate the complexity of features in the product backlog. For the estimation process, we use a simplified Fibonacci sequence: 0, 1, 2, 3, 5, 8, 13, 20, 40, 100.\n","title":"Story pointing","type":"articles"},{"content":"Your software team has a process that use to complete work. Normalizing that process–i.e., establishing it as a workflow–makes it structured and repeatable, which, in turn, makes it scalable. With your development team, you can take an iterative approach to workflow management because it helps you meet your goals faster and exemplifies your team culture.\nSimple is always best When implementing a workflow for the team, always start simple. Fight the temptation to spend weeks (over-)engineering it. Overly complex workflows are hard to understand and adopt–not to mention adapt. Here are some necessary workflow states:\nTO DO – Work that has not been started\nIN PROGRESS – Work that is actively being looked at by the team.\nCODE REVIEW – Work that is completed, but awaiting review.\nAWAITING QA – Work that has been implemented, but is still waiting for a tester review\nREADY TO MERGE – Code that has been reviewed and is ready to merge into the master or release branch.\nDONE – Work that is completely finished and meets the team’s definition of done. In your issue tracker, these statuses flow from one to the next using transitions which structure the workflow.\nEach state in the workflow doesn’t need to be handled by a different person. As an agile team matures, developers feel more and more of the work–from design all the way through to delivery. An independent group that can handle the different job is one of the hallmarks of agility, after all, of the hallmarks of agility, after all. The processes and steps required between each status Approved At this stage the developer is to create a new Branch, following the naming convention:\nticket – description\ne.g.\nDEV-3896 – Issues in Meter Group Analysis graph and drill down.\nCoding Complete Commit code to the server, using user branch above, this will allow for the code reviewer the ability to check this version\nHappy code is all okay QA will now take this branch and run it on their local machine to QA the story.\nAny issues new sub-tasks of the story will be created.\nPassed QA Taking the branched code and moving the branch back to the trunk or the current main branch for that sprint.\nMerged Branch Ticket is closed\nReference: Using workflows for fun \u0026amp; profit\n","date":"10 August 2018","externalUrl":null,"permalink":"/development-process-flow/","section":"Articles","summary":"Your software team has a process that use to complete work. Normalizing that process–i.e., establishing it as a workflow–makes it structured and repeatable, which, in turn, makes it scalable. With your development team, you can take an iterative approach to workflow management because it helps you meet your goals faster and exemplifies your team culture.\n","title":"Development Process Flow","type":"articles"},{"content":"It is sometimes useful to know which database you are connected to, here is a simple method that pulls apart the connection string and provides you with the section you request.\nprivate static string GetSection(string section) { var connectionString = string.Empty; Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(\u0026quot;/MyWebSiteRoot\u0026quot;); ConnectionStringSettings connString;\nif (rootWebConfig.ConnectionStrings.ConnectionStrings.Count \u0026gt; 0) { connString = rootWebConfig.ConnectionStrings.ConnectionStrings[\u0026ldquo;Entities\u0026rdquo;]; if (connString != null) connectionString = connString.ConnectionString; }\nstring[] parts = connectionString.Split(\u0026rsquo;;\u0026rsquo;);\nfor (int i = 0; i \u0026lt; parts.Length; i++) { string part = parts[i].Trim().ToLowerInvariant(); if (part.StartsWith($\u0026quot;{section}=\u0026quot;)) { return part.Replace($\u0026quot;{section}=\u0026quot;, \u0026ldquo;\u0026rdquo;); } }\nreturn \u0026ldquo;Unknown\u0026rdquo;; }\n","date":"31 July 2018","externalUrl":null,"permalink":"/break-apart-the-connection-string/","section":"Articles","summary":"It is sometimes useful to know which database you are connected to, here is a simple method that pulls apart the connection string and provides you with the section you request.\nprivate static string GetSection(string section) { var connectionString = string.Empty; Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(\"/MyWebSiteRoot\"); ConnectionStringSettings connString;\nif (rootWebConfig.ConnectionStrings.ConnectionStrings.Count \u003e 0) { connString = rootWebConfig.ConnectionStrings.ConnectionStrings[“Entities”]; if (connString != null) connectionString = connString.ConnectionString; }\nstring[] parts = connectionString.Split(’;’);\nfor (int i = 0; i \u003c parts.Length; i++) { string part = parts[i].Trim().ToLowerInvariant(); if (part.StartsWith($\"{section}=\")) { return part.Replace($\"{section}=\", “”); } }\nreturn “Unknown”; }","title":"Break apart the connection string","type":"articles"},{"content":"The 3 equal signs mean “equality without type coercion”. Using the triple equals, the values must be equal in type as well.\n0 == false // true 0 === false // false, because they are of a different type 1 == \"1\" // true, automatic type conversion for value only 1 === \"1\" // false, because they are of a different type null == undefined // true null === undefined // false '0' == false // true '0' === false // false ","date":"18 May 2018","externalUrl":null,"permalink":"/difference-between-and-in-javascript/","section":"Articles","summary":"The 3 equal signs mean “equality without type coercion”. Using the triple equals, the values must be equal in type as well.\n0 == false // true 0 === false // false, because they are of a different type 1 == \"1\" // true, automatic type conversion for value only 1 === \"1\" // false, because they are of a different type null == undefined // true null === undefined // false '0' == false // true '0' === false // false","title":"Difference between == and === in JavaScript","type":"articles"},{"content":"","date":"18 May 2018","externalUrl":null,"permalink":"/categories/javascript/","section":"Categories","summary":"","title":"JavaScript","type":"categories"},{"content":"Install ASP.NET and Web Tools 2012.2 Update. This update integrates help pages into the Web API project template.\nNext, create a new ASP.NET MVC 4 project and select the Web API project template. The project template creates an example API controller named ValuesController. The template also creates the API help pages. All of the code files for the help page are placed in the Areas folder of the project.\nWhen you run the application, the home page contains a link to the API help page. From the home page, the relative path is /Help.\nThis link brings you to an API summary page.\nThe MVC view for this page is defined in Areas/HelpPage/Views/Help/Index.cshtml. You can edit this page to modify the layout, introduction, title, styles, and so forth.\nThe main part of the page is a table of APIs, grouped by controller. The table entries are generated dynamically, using the IApiExplorer interface. (I’ll talk more about this interface later.) If you add a new API controller, the table is automatically updated at run time.\nThe “API” column lists the HTTP method and relative URI. The “Description” column contains documentation for each API. Initially, the documentation is just placeholder text. In the next section, I’ll show you how to add documentation from XML comments.\nEach API has a link to a page with more detailed information, including example request and response bodies.\nAdding Help Pages to an Existing Project You can add help pages to an existing Web API project by using NuGet Package Manager. This option is useful you start from a different project template than the “Web API” template.\nFrom the Tools menu, select Library Package Manager, and then select Package Manager Console. In the Package Manager Console window, type one of the following commands:\nFor a C# application: Install-Package Microsoft.AspNet.WebApi.HelpPage\nFor a Visual Basic application: Install-Package Microsoft.AspNet.WebApi.HelpPage.VB\nThere are two packages, one for C# and one for Visual Basic. Make sure to use the one that matches your project.\nThis command installs the necessary assemblies and adds the MVC views for the help pages (located in the Areas/HelpPage folder). You’ll need to manually add a link to the Help page. The URI is /Help. To create a link in a razor view, add the following:\n@Html.ActionLink(\"API\", \"Index\", \"Help\", new { area = \"\" }, null) Also, make sure to register areas. In the Global.asax file, add the following code to the Application_Start method, if it is not there already:\nprotected void Application_Start() { // Add this code, if not present. AreaRegistration.RegisterAllAreas(); // \u0026hellip; }\nAdding API Documentation By default, the help pages have placeholder strings for documentation. You can use XML documentation commentsto create the documentation. To enable this feature, open the file Areas/HelpPage/App_Start/HelpPageConfig.cs and uncomment the following line:\nconfig.SetDocumentationProvider(new XmlDocumentationProvider( HttpContext.Current.Server.MapPath(\"~/App_Data/XmlDocument.xml\"))); Now enable XML documentation. In Solution Explorer, right-click the project and select Properties. Select the Buildpage.\nUnder Output, check XML documentation file. In the edit box, type “App_Data/XmlDocument.xml”.\nNext, open the code for the ValuesController API controller, which is defined in /Controllers/ValuesControler.cs. Add some documentation comments to the controller methods. For example:\n/// \u0026lt;summary\u0026gt; /// Gets some very important data from the server. /// \u0026lt;/summary\u0026gt; public IEnumerable\u0026lt;string\u0026gt; Get() { return new string[] { \"value1\", \"value2\" }; } /// \u0026lt;summary\u0026gt; /// Looks up some data by ID. /// \u0026lt;/summary\u0026gt; /// \u0026lt;param name=\u0026ldquo;id\u0026rdquo;\u0026gt;The ID of the data.\u0026lt;/param\u0026gt; public string Get(int id) { return \u0026ldquo;value\u0026rdquo;; }\nNote\nTip: If you position the caret on the line above the method and type three forward slashes, Visual Studio automatically inserts the XML elements. Then you can fill in the blanks.\nNow build and run the application again, and navigate to the help pages. The documentation strings should appear in the API table.\nThe help page reads the strings from the XML file at run time. (When you deploy the application, make sure to deploy the XML file.)\nUnder the Hood The help pages are built on top of the ApiExplorer class, which is part of the Web API framework. The ApiExplorerclass provides the raw material for creating a help page. For each API, ApiExplorer contains an ApiDescription that describes the API. For this purpose, an “API” is defined as the combination of HTTP method and relative URI. For example, here are some distinct APIs:\nGET /api/Products GET /api/Products/{id} POST /api/Products If a controller action supports multiple HTTP methods, the ApiExplorer treats each method as a distinct API.\nTo hide an API from the ApiExplorer, add the ApiExplorerSettings attribute to the action and set IgnoreApi to true.\n[ApiExplorerSettings(IgnoreApi=true)] public HttpResponseMessage Get(int id) { } You can also add this attribute to the controller, to exclude the entire controller.\nThe ApiExplorer class gets documentation strings from the IDocumentationProvider interface. As you saw earlier, the Help Pages library provides an IDocumentationProvider that gets documentation from XML documentation strings. The code is located in /Areas/HelpPage/XmlDocumentationProvider.cs. You can get documentation from another source by writing your own IDocumentationProvider. To wire it up, call the SetDocumentationProviderextension method, defined in HelpPageConfigurationExtensions\nApiExplorer automatically calls into the IDocumentationProvider interface to get documentation strings for each API. It stores them in the Documentation property of the ApiDescription and ApiParameterDescription objects.\nOrginal article https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/creating-api-help-pages\n","date":"15 May 2018","externalUrl":null,"permalink":"/creating-api-help-pages/","section":"Articles","summary":"Install ASP.NET and Web Tools 2012.2 Update. This update integrates help pages into the Web API project template.\nNext, create a new ASP.NET MVC 4 project and select the Web API project template. The project template creates an example API controller named ValuesController. The template also creates the API help pages. All of the code files for the help page are placed in the Areas folder of the project.\n","title":"Creating API Help Pages","type":"articles"},{"content":"","date":"15 May 2018","externalUrl":null,"permalink":"/categories/rest/","section":"Categories","summary":"","title":"REST","type":"categories"},{"content":"If you are serious about using SOAP, it won’t be long before you find out that if you need a full ISO date in the XML, it will not work using C# and SOAP, as DateTimeOffset is not supported from Microsoft.\nHere is how you go about ensuring that you deliver an ISO DateTime formatted field in SOAP.\nFirst, you’ll need to create a struct to hold the ISO 8601 Date Time Offset, and we will use IXmlSerializable interface which provides custom formatting for XML serialisation and deserialization.\npublic struct Iso8601SerializableDateTimeOffset : IXmlSerializable { public DateTimeOffset value; public Iso8601SerializableDateTimeOffset(DateTimeOffset value) { this.value = value; }\npublic static implicit operator Iso8601SerializableDateTimeOffset(DateTimeOffset value) { return new Iso8601SerializableDateTimeOffset(value); }\npublic static implicit operator DateTimeOffset(Iso8601SerializableDateTimeOffset instance) { return instance.value; }\npublic static bool operator ==(Iso8601SerializableDateTimeOffset a, Iso8601SerializableDateTimeOffset b) { return a.value == b.value; }\npublic static bool operator !=(Iso8601SerializableDateTimeOffset a, Iso8601SerializableDateTimeOffset b) { return a.value != b.value; }\npublic static bool operator \u0026lt;(Iso8601SerializableDateTimeOffset a, Iso8601SerializableDateTimeOffset b) { return a.value \u0026lt; b.value; }\npublic static bool operator \u0026gt;(Iso8601SerializableDateTimeOffset a, Iso8601SerializableDateTimeOffset b) { return a.value \u0026gt; b.value; }\npublic override bool Equals(object o) { if (o is Iso8601SerializableDateTimeOffset) return value.Equals(((Iso8601SerializableDateTimeOffset)o).value); else if (o is DateTimeOffset) return value.Equals((DateTimeOffset)o); else return false; }\npublic override int GetHashCode() { return value.GetHashCode(); }\npublic XmlSchema GetSchema() { return null; }\npublic void ReadXml(XmlReader reader) { var text = reader.ReadElementString(); value = DateTimeOffset.ParseExact(text, format: \u0026ldquo;o\u0026rdquo;, formatProvider: null); }\npublic override string ToString() { return value.ToString(format: \u0026ldquo;o\u0026rdquo;); }\npublic string ToString(string format) { return value.ToString(format); }\npublic void WriteXml(XmlWriter writer) { writer.WriteString(value.ToString(format: \u0026ldquo;o\u0026rdquo;)); } }\nWe also need to cater for Json Date Time Offsets too, so we will write a converter\npublic class UtcDateTimeOffsetConverter : Newtonsoft.Json.Converters.IsoDateTimeConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value is Iso8601SerializableDateTimeOffset) { var date = (Iso8601SerializableDateTimeOffset)value; value = date.value; } base.WriteJson(writer, value, serializer); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { object value = base.ReadJson(reader, objectType, existingValue, serializer); if (value is Iso8601SerializableDateTimeOffset) { var date = (Iso8601SerializableDateTimeOffset)value; value = date.value; } return value; } }\nNext, we need to implement it in an object model, with a slight twist as you can not use the Iso8601SerializableDateTimeOffset struct directly, to do this we need to wrap the result into a string property\npublic class Foo { public Guid Id { get; set; } [JsonConverter(typeof(UtcDateTimeOffsetConverter))] [XmlElement(\u0026ldquo;AcquireDate\u0026rdquo;)] public string acquireDateForXml { get { return AcquireDate.ToString(); } set { AcquireDate = DateTimeOffset.Parse(value); } }\n[XmlIgnore] public Iso8601SerializableDateTimeOffset? AcquireDate; }\nThat is it, job done\nhttps://github.com/BryanAvery/DateTimeOffsetSOAP\nDateTimeOffsetforSOAP\n","date":"10 May 2018","externalUrl":null,"permalink":"/datetimeoffset-for-soap/","section":"Articles","summary":"If you are serious about using SOAP, it won’t be long before you find out that if you need a full ISO date in the XML, it will not work using C# and SOAP, as DateTimeOffset is not supported from Microsoft.\n","title":"DateTimeOffset for SOAP","type":"articles"},{"content":"","date":"10 May 2018","externalUrl":null,"permalink":"/categories/soap/","section":"Categories","summary":"","title":"SOAP","type":"categories"},{"content":"Here is a simple example of how to use Bing Maps in an MVC application.\nI am using Bing Maps V8 which is the current version of Microsoft.\nAlso, nothing that document.ready will fire long before the map script loads as it loads asynchronously. Sometimes document.ready will fire before the page is loaded which means the map div might not even be available. To overcome this, we are using the callback parameter of the map script UR: for example:\nhttp://www.bing.com/api/maps/mapcontrol?callback=LoadMap\nBingMapsDemo\nThe Microsoft documentation can be found here:\nhttps://www.bing.com/api/maps/sdkrelease/mapcontrol/isdk/Overview#JS\nTo setup a Key you can do this quite easily at the Bing Maps Portal website:\nhttps://www.bingmapsportal.com\n","date":"1 May 2018","externalUrl":null,"permalink":"/bing-maps-in-an-mvc-application/","section":"Articles","summary":"Here is a simple example of how to use Bing Maps in an MVC application.\nI am using Bing Maps V8 which is the current version of Microsoft.\nAlso, nothing that document.ready will fire long before the map script loads as it loads asynchronously. Sometimes document.ready will fire before the page is loaded which means the map div might not even be available. To overcome this, we are using the callback parameter of the map script UR: for example:\n","title":"Bing Maps in an MVC Application","type":"articles"},{"content":"","date":"1 May 2018","externalUrl":null,"permalink":"/categories/mapping/","section":"Categories","summary":"","title":"Mapping","type":"categories"},{"content":"(Added LazyCache in to the Testing)\nOne of the essential factors in building high-performance, scalable Web applications is the ability to store items, whether data objects, pages, or even parts of a page in memory the initial time they are requested. You can save these items on the Web server or other software in the request stream, such as a proxy server or at the browser. This allows you to avoid recreating information that satisfied a previous request. Known as caching, it will enable you to use many techniques to store page output or application data across HTTP requests and reuse it. When the server does not have to recreate information you save time and resources, and throughput and scalability increase.\nIt is possible to obtain significant performance improvements in ASP.NET applications by caching frequently requested objects and data in either the Application or Cache classes. While the Cache class indeed offers far more flexibility and control, it only appears to provide a marginal advantage regarding increased throughput over the Application class for caching. It would be challenging to develop a testing scheme that could accurately measure the potential benefits of the Cache class’s built-in management of lesser-used objects through the scavenging process as opposed to the fact that Application does not offer this feature. The developer needs to decide this case and should be based on the needs and convenience of the project and its usage patterns.\nIn the article, I’ll be looking at the application caching and what is the most effective and scalable options. If you would like to know more about the web caching then take a look at the Microsoft Caching Architecture Guide for .NET Framework Applications\nSo we all know that caching increases performance, what I am not getting into here is when it should be used or when it shouldn’t be used. I’m more interested in the performance and scalability of the caching used.\nThe performance testing I am going to use the following different caching methods:\nNo Caching Memory Cache Memory Cache using Statics Memory Cache using Singleton HttpRuntime Cache Redis Cache (You’ll need to setup a local Redis server in order to see the results, here is the Windows Redis Service installer) LazyCache I’ve tried to provide some different options that are available for Caching, if you know of any others, please let me know and I’ll add them to this post.\nThere are two types of tests I am using a small test which waits for 30 milliseconds and then returns back the current date and time:\nThread.Sleep(30); return System.DateTime.UtcNow.ToString(CultureInfo.InvariantCulture); then a test to generate a much large object of 267 Mb\npublic IEnumerable\u0026lt;Block\u0026gt; GetData() { // should eat around 267 Mb of RAM. var blocks = new Block[512 * 512 * 1]; for (var i = 0; i \u0026amp;lt; (512 * 512) * 1; i++) { blocks[i] = new Block(); } return blocks; }\nBoth are straightforward tests, by no means are they an accurate representation of real-world methods, but they do show you how it affects the performance when using different Caching.\nThe idea is to iterate around these test 1,000 times and record how long it takes for each test, what I don’t do here is work out the amount of memory is being used (if you know of an easy way to include this, please let me know).\nI won’t go into great details here on the results of the tests as I think you’ll find them self-explanatory in the test application, attached at the bottom of this post.\nFew things to note about the testing and results is that you should use a Paralling process for the examination, as this will be much closer to the real world multi-threading environment.\nAlso, careful consideration should be given to using locking in the Cache module, as you don’t want the same cache key function running while another one is trying to process the same function, it should wait until the process has finished and stored it into the cache to increase performance.\nHere is the sample code with different sample tests showing how useful each option is\nCache\n","date":"26 April 2018","externalUrl":null,"permalink":"/caching-to-improve-the-user-experence/","section":"Articles","summary":"(Added LazyCache in to the Testing)\nOne of the essential factors in building high-performance, scalable Web applications is the ability to store items, whether data objects, pages, or even parts of a page in memory the initial time they are requested. You can save these items on the Web server or other software in the request stream, such as a proxy server or at the browser. This allows you to avoid recreating information that satisfied a previous request. Known as caching, it will enable you to use many techniques to store page output or application data across HTTP requests and reuse it. When the server does not have to recreate information you save time and resources, and throughput and scalability increase.\n","title":"Caching to improve the user experience","type":"articles"},{"content":"It has been quite sometime that SignalR has been around, 2014, so why are not more people using it? First what is SignalR?\nASP.NET SignalR is a library for ASP.NET developers that makes developing real-time web functionality easy. SignalR allows bi-directional communication between server and client. Servers can now push content to connected clients instantly as it becomes available. SignalR supports Web Sockets and falls back to other compatible techniques for older browsers. SignalR includes APIs for connection management (for instance, connect and disconnect events), grouping connections, and authorisation.\nFor further information check https://www.asp.net/signalr\nCould it because people just don’t get it or really understand what it can do, or perhaps they hit issues without realising they don’t understand the structure? Whatever the reason people are not using SignalR, I’m going to provide a useful sample application to get you off on the right footing.\nThere are a lot of different samples and information on how to use SignalR, but I’m always a firm believer of KISS (Keep It Simple Stupid).\nThere are two primary sides to SignalR, the client side and the server hubs, here I have created an MVC application with Individual User Accounts for Authentication.\nFirst, add the SignalR NuGet package\nInstall-Package Microsoft.AspNet.SignalR Then we need to map the Hubs connection to the application.\nTo enable SignalR in your application, create a class called Startup with the following:\nusing Microsoft.Owin; using Owin; using MyWebApplication; namespace MyWebApplication { public class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } } }\nWhat is important here is that app.MapSignalR() is the last to be called, and this is because any changes to the app need to be done before you call the mapping. The incorrect order got me once when we had some custom Authentication, and it was not being passed to SignalR hubs.\nI won’t be going into how you go about setting up the step by step process, as this is documented in many places, and also comes in the readme.txt file as part of the NuGet package.\nWhat I will be adding is the Authorization to the project, which is covered by Microsoft in Authentication and Authorization for SignalR Hubs.\nWhat is important to note how the connection is handled, we are using a class called SignalRConnectionManager, and this controls the connections based on the username coming from the context and the connection id which also comes from the context.\npublic class SignalRConnectionManager\u0026lt;T\u0026gt; : IDisposable { private readonly ConcurrentDictionary\u0026lt;T, HashSet\u0026lt;string\u0026gt;\u0026gt; _connections = new ConcurrentDictionary\u0026lt;T, HashSet\u0026lt;string\u0026gt;\u0026gt;(); public int Count { get { return _connections.Count; } }\n/// \u0026lt;summary\u0026gt; /// Attempts to add the specified userid and connectionid /// \u0026lt;/summary\u0026gt; public void Add(T userid, string connectionid) { HashSet\u0026lt;string\u0026gt; connections = _connections.GetOrAdd(userid, new HashSet\u0026lt;string\u0026gt;());\nlock (connections) { connections.Add(connectionid); } }\npublic IEnumerable\u0026lt;string\u0026gt; Connections(T userid) { HashSet\u0026lt;string\u0026gt; connections; if (_connections.TryGetValue(userid, out connections)) { return connections; }\nreturn Enumerable.Empty\u0026lt;string\u0026gt;(); }\npublic IEnumerable\u0026lt;T\u0026gt; UserIds() { return _connections.Keys; }\n/// \u0026lt;summary\u0026gt; /// Attempts to remove a connectionid that has the specified userid /// \u0026lt;/summary\u0026gt; public void Remove(T userid, string connectionid) { HashSet\u0026lt;string\u0026gt; connections; if (!_connections.TryGetValue(userid, out connections)) { return; }\nlock (connections) { connections.Remove(connectionid);\nif (connections.Count == 0) { HashSet\u0026lt;string\u0026gt; emptyConnections; _connections.TryRemove(userid, out emptyConnections); } } }\n#region IDisposable Support\nprivate bool disposedValue = false; // To detect redundant calls\nprotected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { _connections.Clear(); }\n// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null.\ndisposedValue = true; } }\n// This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); }\n#endregion IDisposable Support }\nClient Code In my case I’m going to be looking at JavaScript within a C# MVC application, which looks like this:\n\u0026lt;p\u0026gt;SignalR\u0026lt;/p\u0026gt; \u0026lt;!--The jQuery library is required. --\u0026gt; \u0026lt;script src=\"~/Scripts/jquery-1.10.2.js\"\u0026gt;\u0026lt;/script\u0026gt; \u0026lt;!--Reference the SignalR library. --\u0026gt; \u0026lt;script src=\"~/Scripts/jquery.signalR-2.2.3.min.js\"\u0026gt;\u0026lt;/script\u0026gt; \u0026lt;!--Reference the auto generated SignalR hub script. --\u0026gt; \u0026lt;script src=\"~/signalr/hubs\"\u0026gt;\u0026lt;/script\u0026gt; \u0026lt;!\u0026ndash;Add script to update the page and send messages - SignalR - HeartBeat.\u0026ndash;\u0026gt; \u0026lt;script type=\u0026ldquo;text/javascript\u0026rdquo;\u0026gt; $(function () { // Declare a proxy to reference the hub. var heartBeat = $.connection.heartBeatHub;\nheartBeat.client.broadcastMessage = function (html) { $(\u0026rsquo;#message\u0026rsquo;).html(html).fadeIn(); };\nif ($.connection.hub \u0026amp;\u0026amp; $.connection.hub.state === $.signalR.connectionState.disconnected) { $.connection.hub.start() .done(function () { console.log(\u0026lsquo;SignalR now connected, connection ID=\u0026rsquo; + $.connection.hub.id); heartBeat.server.send(\u0026lsquo;Heart beat listening\u0026rsquo;); console.log(\u0026ldquo;Heart beat started\u0026rdquo;) }) .fail(function () { console.log(\u0026lsquo;Could not Connect!\u0026rsquo;); }); } }); \u0026lt;/script\u0026gt; \u0026lt;div id=\u0026ldquo;message\u0026rdquo;\u0026gt; \u0026lt;/div\u0026gt;\ntwo important lines in this code are:\nReference the auto generated SignalR hub script\n\u0026lt;script src=\"~/signalr/hubs\"\u0026gt;\u0026lt;/script\u0026gt; Declaring the proxy to reference the hub, you’ll notice the case of the letter ‘h’ is different the the C# code, this is important otherwise you will get a JavaScript error in your browser.\nvar heartBeat = $.connection.heartBeatHub; Another important thing to note is that you should only start the hub once, no matter how many SignalR endpoints you have, and you place the listening code within the done section of hub, I’ve commented out another listening hub in this sample code:\nif ($.connection.hub \u0026amp;\u0026amp; $.connection.hub.state === $.signalR.connectionState.disconnected) { $.connection.hub.start() .done(function () { console.log('SignalR now connected, connection ID=' + $.connection.hub.id); heartBeat.server.send('Heart beat listening'); console.log(\"Heart beat started\") //anotherHub.server.send('Another hub listening'); }) .fail(function () { console.log('Could not Connect!'); }); } That is it for now, a good clean SignalR project, and here it is: SignalR\nhttps://github.com/BryanAvery/Signalr\n","date":"25 April 2018","externalUrl":null,"permalink":"/signalr-the-right-way/","section":"Articles","summary":"It has been quite sometime that SignalR has been around, 2014, so why are not more people using it? First what is SignalR?\nASP.NET SignalR is a library for ASP.NET developers that makes developing real-time web functionality easy. SignalR allows bi-directional communication between server and client. Servers can now push content to connected clients instantly as it becomes available. SignalR supports Web Sockets and falls back to other compatible techniques for older browsers. SignalR includes APIs for connection management (for instance, connect and disconnect events), grouping connections, and authorisation.\n","title":"SignalR – the right way","type":"articles"},{"content":"In theory, Async unit testing seems easy, run the Async, wait until it is finished and look at the results. But as you will find out it is not that easy.\nHere is the official approach to Async unit testing\n[TestMethod] public void FourDividedByTwoIsTwo() { GeneralThreadAffineContext.Run(async () =\u0026gt; { int result = await MyClass.Divide(4, 2); Assert.AreEqual(2, result); }); } [TestMethod] [ExpectedException(typeof(DivideByZeroException))] public void DenominatorIsZeroThrowsDivideByZero() { GeneralThreadAffineContext.Run(async () =\u0026gt; { await MyClass.Divide(4, 0); }); }\nHang on what is GeneralThreadAffineContext, it a Utility code originally distributed as part of the Async CTP, and the project file can be found here: AsyncTestUtilities\nOriginal article: Async Unit Tests, Part 2: The Right Way\n","date":"10 April 2018","externalUrl":null,"permalink":"/async-unit-tests/","section":"Articles","summary":"In theory, Async unit testing seems easy, run the Async, wait until it is finished and look at the results. But as you will find out it is not that easy.\nHere is the official approach to Async unit testing\n","title":"Async Unit Tests","type":"articles"},{"content":"Well, as web developers, we are always dealing with JSON data which are coming from different sources. Either we are serialising our entities, or it’s coming from the external sources like third-party services and so on.\nIf the data is coming from an external source, one standard requirement is to always de-serialise it back to the data model to be able to process the data. Creating data model for JSON data is not the most exciting work in the world, especially when the data model is a bit nested and complex.\nFortunately, there is a very nice feature in Visual Studio which makes the life much more manageable. This feature is called Paste Special.\nTo take advantage, you first need to Copy the JSON data. Imaging there is JSON data as follow:\n{ \"glossary\": { \"title\": \"example glossary\", \"GlossDiv\": { \"title\": \"S\", \"GlossList\": { \"GlossEntry\": { \"ID\": \"SGML\", \"SortAs\": \"SGML\", \"GlossTerm\": \"Standard Generalized Markup Language\", \"Acronym\": \"SGML\", \"Abbrev\": \"ISO 8879:1986\", \"GlossDef\": { \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\", \"GlossSeeAlso\": [\"GML\", \"XML\"] }, \"GlossSee\": \"markup\" } } } } } And we require creating the data model for that. To do so, just Copy the data in memory and go to Visual Studio, create a new class (or an existing one where we intend to have our data model).\nFrom the Edit menu in Visual Studio, select the Paste Special and from the submenu, Paste JSON As Classes.\nThen, the data model will generate as follow:\npublic class Rootobject { public Glossary glossary { get; set; } } public class Glossary { public string title { get; set; } public Glossdiv GlossDiv { get; set; } }\npublic class Glossdiv { public string title { get; set; } public Glosslist GlossList { get; set; } }\npublic class Glosslist { public Glossentry GlossEntry { get; set; } }\npublic class Glossentry { public string ID { get; set; } public string SortAs { get; set; } public string GlossTerm { get; set; } public string Acronym { get; set; } public string Abbrev { get; set; } public Glossdef GlossDef { get; set; } public string GlossSee { get; set; } }\npublic class Glossdef { public string para { get; set; } public string[] GlossSeeAlso { get; set; } }\nAs if by magic you see the initial data model has been created for us\nAs you may have noticed, there is one more option under Paste Special menu item, named Paste XML As Classes. This item does the same thing but for XML data. That means you need to copy your XML data to the memory and from the Paste Special menu item, choose Paste XML As Classes this time, to have your data model generated.\nOriginal post ‘Paste Special’: a less well-known feature in Visual Studio\n","date":"9 April 2018","externalUrl":null,"permalink":"/generate-c-classes-from-json-responses/","section":"Articles","summary":"Well, as web developers, we are always dealing with JSON data which are coming from different sources. Either we are serialising our entities, or it’s coming from the external sources like third-party services and so on.\n","title":"Generate C# Classes from JSON Responses","type":"articles"},{"content":"","date":"9 April 2018","externalUrl":null,"permalink":"/categories/visual-studio-2013/","section":"Categories","summary":"","title":"Visual Studio 2013","type":"categories"},{"content":"The Repository Pattern used to be the next big thing when it was used, but over time it got replaced by frameworks such as the Entity Framework and LINQ, which provided much more functionality and flexibility.\nI started working on an external customers REST API then I realised that the Repository Pattern would work perfectly here.\nLet’s recap the Repository Pattern. The Repository Pattern has gained quite a bit of popularity since it was first introduced as a part of Domain-Driven Design in 2004. Primarily, it provides an abstraction of data, so that your application can work with a pure abstraction that has an interface approximating that of a collection. Adding, removing, updating, and selecting items from this collection is done through a series of straightforward methods, without the need to deal with database concerns like connections, commands, cursors, or readers. Using this pattern can help achieve loose coupling and can keep domain objects persistence ignorant. Although the pattern is prevalent (or perhaps because of this), it is also frequently misunderstood and misused. There are many different ways to implement the Repository pattern. Let’s consider a few of them, and their merits and drawbacks.\nRepository Per Entity or Business Object The most straightforward approach, especially with an existing system, is to create a new Repository implementation for each business object you need to store to or retrieve from your persistence layer. Further, you should only implement the specific methods you are calling in your application. Avoid the trap of creating a “standard” repository class, base class, or default interface that you must implement for all repositories. Yes, if you need to have an Update or a Delete method, you should strive to make its interface consistent (does Delete take an ID, or does it take the object itself?). Don’t implement a Delete method on your LookupTableRepository that you’re only ever going to be calling List(). The most significant benefit of this approach is YAGNI – you won’t waste any time implementing methods that never get called.\nGeneric Repository Interface Another approach is to go ahead and create a simple, generic interface for your Repository. You can constrain what kind of types it works with to be of a specific type or to implement a particular interface (e.g. ensuring it has an Id property, as is done below using a base class). An example of a generic C# repository interface might be:\npublic interface IRepository\u0026lt;T\u0026gt; where T : EntityBase { T GetById(int id); IEnumerable\u0026lt;T\u0026gt; List(); IEnumerable\u0026lt;T\u0026gt; List(Expression\u0026lt;Func\u0026lt;T, bool\u0026gt;\u0026gt; predicate); void Add(T entity); void Delete(T entity); void Edit(T entity); } public abstract class EntityBase { public int Id { get; protected set; } } The advantage of this approach is that it ensures you have a common interface for working with any of your objects. You can also simplify the implementation by using a Generic Repository Implementation (below). Note that taking in a predicate eliminates the need to return an IQueryable since any filter details can be passed into the repository. This can still lead to leaking of data access details into calling code, though. Consider using the Specification pattern (described below) to alleviate this issue if you encounter it.\nGeneric Repository Implementation Assuming you create a Generic Repository Interface, you can implement the interface generically as well. Once this is done, you can quickly develop repositories for any given type without having to write any new code, and your classes the declare dependencies can merely specify IRepository\u0026lt;Item\u0026gt; as the type, and it’s easy for your IoC container to match that up with a Repository\u0026lt;Item\u0026gt; implementation. You can see an example Generic Repository Implementation, using Entity Framework, here.\npublic class Repository\u0026lt;T\u0026gt; : IRepository\u0026lt;T\u0026gt; where T : EntityBase { private readonly ApplicationDbContext _dbContext; public Repository(ApplicationDbContext dbContext) { _dbContext = dbContext; }\npublic virtual T GetById(int id) { return _dbContext.Set\u0026lt;T\u0026gt;().Find(id); }\npublic virtual IEnumerable\u0026lt;T\u0026gt; List() { return _dbContext.Set\u0026lt;T\u0026gt;().AsEnumerable(); }\npublic virtual IEnumerable\u0026lt;T\u0026gt; List(System.Linq.Expressions.Expression\u0026lt;Func\u0026lt;T, bool\u0026gt;\u0026gt; predicate) { return _dbContext.Set\u0026lt;T\u0026gt;() .Where(predicate) .AsEnumerable(); }\npublic void Insert(T entity) { _dbContext.Set\u0026lt;T\u0026gt;().Add(entity); _dbContext.SaveChanges(); }\npublic void Update(T entity) { _dbContext.Entry(entity).State = EntityState.Modified; _dbContext.SaveChanges(); }\npublic void Delete(T entity) { _dbContext.Set\u0026lt;T\u0026gt;().Remove(entity); _dbContext.SaveChanges(); } }\nNote that in this implementation, all operations are saved as they are performed; there is no Unit of Work being applied. There are a variety of ways in which Unit of Work behaviour can be added to this implementation, the simplest of which being to add an explicit Save() method to the IRepository\u0026lt;T\u0026gt; method, and to only call the underlying SaveChanges() method from this method.\nIQueryable? Another common question with Repositories has to do with what they return. Should they return data, or should they return queries that can be further refined before execution (IQueryable)? The former is safer, but the latter offers a great deal of flexibility. In fact, you can simplify your interface only to provide a single method for reading data if you go the IQueryable route since from there any number of items can be returned.\nA problem with this approach is that it tends to result in business logic bleeding into higher application layers and becoming duplicated there. If the rule for returning valid customers is that they’re not disabled and they’ve bought something in the last year, it would be better to have a method ListValidCustomers() that encapsulates this logic rather than specifying these criteria in lambda expressions in multiple different UI layer references to the repository. Another typical example in real applications is the use of “soft deletes” represented by an IsActive or IsDeleted property on an entity. Once an item has been deleted, 99% of the time it should be excluded from display in any UI scenario, so nearly every request will include something like\n.Where(foo =\u0026gt; foo.IsActive)\nin addition to whatever other filters are present. This is better achieved within the repository, where it can be the default behaviour of the List() method, or the List() method might be renamed to something like ListActive(). If it’s essential to view deleted/inactive items, a unique List method can be used for just this (probably rare) purpose.\nSpecification Repositories that follow the advice of not exposing IQueryable can often become bloated with many custom query methods. The solution to this is to separate queries into their types, using the Specification Design Pattern. The Specification can include the expression used to filter the query, any parameters associated with this expression, as well as how much data the query should return (i.e. “.Include()” in EF/EF Core). Combining the Repository and Specification patterns can be a great way to ensure you follow the Single Responsibility Principle in your data access code. See an example of how to implement a generic repository along with a generic specification in C#.\nRepository Pattern for the REST API Now let’s see if this can work for the REST API, first the HTTP verbs that are used, the primary or most-commonly-used HTTP verbs (or methods, as they are properly called) are POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations, respectively. There are a number of other verbs, too, but are utilized less frequently. Of those less-frequent methods, OPTIONS and HEAD are used more often than others.\nHTTP Verb CRUD POST Create GET Read PUT Update/Replace PATCH Update/Modify DELETE Delete One of the main difference is that the calls to REST API are Asynchronous, and the interface needs to reflect this.\npublic interface IRepository { Task AddAsync\u0026lt;T\u0026gt;(T entity, string requestUri); Task\u0026lt;HttpStatusCode\u0026gt; DeleteAsync(string requestUri); Task EditAsync\u0026lt;T\u0026gt;(T t, string requestUri); Task\u0026lt;T\u0026gt; GetAsync\u0026lt;T\u0026gt;(string path); } In the concrete implementation I am using the HttpClient to connect to the REST API, which needs a few parameters:\nUri of the end point Authorization – type of authorization to be used, default NoAuthHttpSample username – username for basic authorization – default null password – the password for basic authorization – default null A sample application can be found here:\nOriginal reference Repository Pattern A data persistence abstraction\n","date":"6 April 2018","externalUrl":null,"permalink":"/repository-pattern-for-the-rest-api/","section":"Articles","summary":"The Repository Pattern used to be the next big thing when it was used, but over time it got replaced by frameworks such as the Entity Framework and LINQ, which provided much more functionality and flexibility.\n","title":"Repository Pattern – for the REST API","type":"articles"},{"content":"Visual Studio Unit Test Tools comes with another excellent feature to manage unit test as a group /subset, called as “Playlist”. A Playlist is a subset of unit test methods grouped under some category. The Playlist could be a logical subset based on modules, features, layers etc. A Playlist is useful when we want to test a particular set of test cases among all the test methods. In that case, we just create a group of those test cases which may get impacted by our current changes in the actual code, and execute them only to ensure nothing breaks.\nYou can create a playlist either from the Test Explorer or the main menu by navigating to Test –\u0026gt; Playlist. Let’s have a look how we can do that.\nStep 1 : Select Unit Test methods together for which you want to create a playlist. Step 2 : Navigate to Add to Playlist –\u0026gt; New Playlist\nThe rest I’m sure you can work out for yourself, if you want more information on this check out Daily .NET Tips\n","date":"7 March 2018","externalUrl":null,"permalink":"/create-a-subset-of-unit-tests-with-a-playlist/","section":"Articles","summary":"Visual Studio Unit Test Tools comes with another excellent feature to manage unit test as a group /subset, called as “Playlist”. A Playlist is a subset of unit test methods grouped under some category. The Playlist could be a logical subset based on modules, features, layers etc. A Playlist is useful when we want to test a particular set of test cases among all the test methods. In that case, we just create a group of those test cases which may get impacted by our current changes in the actual code, and execute them only to ensure nothing breaks.\n","title":"Create a subset of Unit Tests with a Playlist","type":"articles"},{"content":"When you are dealing with large amounts of data or processes that are very time hungry you sometimes need the ability to timeout that task and continue.\nHere is a snippet of code that loops around that takes 1 second, and you can set a timeout to any time you like, but if it is less than 1 second, it will cancel the task and free up resources.\nclass Program { public static void Main() { int timeOutInMilliseconds = 450; var startTime = DateTime.Now; var cTokenSource = new CancellationTokenSource();\n// Create a cancellation token from CancellationTokenSource var cToken = cTokenSource.Token; // Create a task and pass the cancellation token var t1 = Task\u0026lt;int\u0026gt;.Factory.StartNew(() =\u0026gt; GenerateNumbers(cToken), cToken);\n// to register a delegate for a callback when a cancellation request is made cToken.Register(() =\u0026gt; cancelNotification(cTokenSource));\nwhile (true) { if(t1.IsCompleted) { Console.WriteLine(\u0026ldquo;Finished Processing\u0026rdquo;); break; }\nif (DateTime.Now \u0026gt; startTime.AddMilliseconds(timeOutInMilliseconds)) { Console.WriteLine(\u0026ldquo;Timed out\u0026rdquo;); cTokenSource.Cancel(); break; } }\nConsole.WriteLine(\u0026ldquo;finished\u0026rdquo;); Console.ReadLine(); }\nprivate static Task HandleTimer(CancellationTokenSource cancellationTokenSource) { cancellationTokenSource.Cancel(); Console.WriteLine(\u0026quot;\\nHandler not implemented\u0026hellip;\u0026quot;); return Task.Run(() =\u0026gt; { var a = 0; });\n}\nstatic int GenerateNumbers(CancellationToken cancellationTokenSource) { int i; for (i = 0; i \u0026lt; 10; i++) { Console.WriteLine(\u0026ldquo;Method1 - Number: {0}\u0026rdquo;, i); Thread.Sleep(100);\n// poll the IsCancellationRequested property // to check if cancellation was requested if (cancellationTokenSource.IsCancellationRequested) break; } return i; }\n// Notify when task is cancelled static void cancelNotification(CancellationTokenSource cancellationTokenSource) { cancellationTokenSource.Cancel(); } }\nSource: Parallel\n","date":"23 February 2018","externalUrl":null,"permalink":"/timeout-process/","section":"Articles","summary":"When you are dealing with large amounts of data or processes that are very time hungry you sometimes need the ability to timeout that task and continue.\nHere is a snippet of code that loops around that takes 1 second, and you can set a timeout to any time you like, but if it is less than 1 second, it will cancel the task and free up resources.\n","title":"Timeout Process","type":"articles"},{"content":"Following on from the Search every table and field in a SQL Server Database article I posted last week, I thought it would be useful also to be able to search every column for some text and return where it was found.\nHere is the script that I have produced which does the job and is quick in its response.\nCREATE PROC [SearchAllColumns] ( @SearchStr nvarchar(100) ) AS BEGIN\nSELECT COLUMN_NAME AS \u0026lsquo;ColumnName\u0026rsquo;, TABLE_NAME AS \u0026lsquo;TableName\u0026rsquo; FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME LIKE \u0026lsquo;%\u0026rsquo; + @SearchStr + \u0026lsquo;%\u0026rsquo; ORDER BY TableName, ColumnName;\nEND\n","date":"22 February 2018","externalUrl":null,"permalink":"/search-every-column-in-a-sql-server-database/","section":"Articles","summary":"Following on from the Search every table and field in a SQL Server Database article I posted last week, I thought it would be useful also to be able to search every column for some text and return where it was found.\n","title":"Search every column in a SQL Server Database","type":"articles"},{"content":"Following on from the Search every table and field in a SQL Server Database article I posted last week, I thought it would be useful also to be able to search every column for some text and return where it was found.\nHere is the script that I have produced which does the job and is quick in its response.\nCREATE PROC [SearchAllColumns] ( @SearchStr nvarchar(100) ) AS BEGIN\nSELECT COLUMN_NAME AS \u0026lsquo;ColumnName\u0026rsquo;, TABLE_NAME AS \u0026lsquo;TableName\u0026rsquo; FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME LIKE \u0026lsquo;%\u0026rsquo; + @SearchStr + \u0026lsquo;%\u0026rsquo; ORDER BY TableName, ColumnName;\nEND\n","date":"22 February 2018","externalUrl":null,"permalink":"/search/","section":"Articles","summary":"Following on from the Search every table and field in a SQL Server Database article I posted last week, I thought it would be useful also to be able to search every column for some text and return where it was found.\n","title":"Search every column in a SQL Server Database","type":"articles"},{"content":"In the article we are going to look at the importance of a good version control system, and why it is crucial when it comes to API versioning.\nIt is essential that we deploy a Web API version control from an early stage in our project. Versioning will ensure that the project is built on a solid base and that a standard is maintained. A good version control system will enable us to collaborate and scale in a managed way, and as such will provide our customers with a more straightforward progression through our upgrades.\nThe first point to note we should always version our Web API, while at the same time keeping as much of the same URI as possible, with the possibility of newer versions having a different URI and a clear upgrade path.\nWhat is versioning? Versioning is a thoughtful application of changes to a system that is already in production.\nThere are two types of versioning, they are:\nVersioning Data – changing the way we lay out our data structures, name things and so on Version SOAP Endpoints – adding or removing functionality, such as functions that can be called or changing parameters that can be called on those endpoints Plan Versioning How do we handle versioning? We are producing a plan for the first release, and we need to do the following:\nAt the start Pick a version-able identifier pick a versioning pattern Version-able identifiers XML Data: XML Namespace Things that listen at URL’s: URL Path Numbering Pattern https://yoururl.co.uk/[service name]/major.[minor].[build[ Each number increases monotonically: 1,2,3,4, …., 9, 10, 11 Date Pattern https://yoururl.co.uk/[service name]/[yyyy]/[mm]/[dd] https://yoururl.co.uk/[service name]/[yyyy].[mm].[dd] The only time we ever need to version is when we change the contract with the client, we can change the contract in one of three ways:\nData Add a new type Removing a type Change fields Required fields SOAP Add/remove methods Change parameter names In session: change the set of initiating/termination actions REST Change URI structure Add methods Versioning Data There are times when you need to version the data:\nReasons to version data Name chooser picked terrible names (aka renames) Adding/removing fields Things to handle upon versioning data Co-existing old/new clients Reason not to version data Re-ordering for aesthetic reasons New Members If a new member is required, define sensible default Caveat: if no sensible default exists, you have a severe bug in a previous version If you think you have no reasonable default and customers won’t change, you will suddenly find a sensible default Place at the end Some clients may be ordinal dependent, not name Use DataMember.Order property Or inherit Data Transformation Object if new item breaks old clients Versioning SOAP Endpoints Reasons to version endpoints Name chooser picked terrible names (aka renames) Adding methods Removing methods Updating method parameters (new version of old type) Adding terminating functions (might already exist) Things to handle upon versioning endpoints Update old to call out to controller properly Reasons not to version endpoint Re-ordering for esthetic reasons (don’t do this!) Handle Versioning Keep services light Keep details in separate class Use MVC type pattern DTO is Model Service is View “Separate class” is Controller Benefits Minimize code churn in services Keep logic mapping DTO to Business in one place Key Points Keep service code clean, simple. Think of service as a machine UI to the real object model. Let internal logic worry about mapping DTO to the business objects. Handle upgrade in one place, away from service. Versioning REST Endpoints Reasons to version REST endpoints Name chooser picked terrible names Paths don’t make sense Updating data types, parameters (new version of old model) Things to handle upon versioning endpoints Update old to call out to controller properly Reasons not to version endpoint Supporting more of Uniform Interface (GET | HEAD, PUT, POST, DELETE) Where to version? New set of services in new directory Pros: clean separation, small files, easy to read, allows for more natural deletion later Cons: not necessary, moves logic to new file Keep everything in one file, add new UriTemplates Pros: All URLs in one place, easy to see what uses code, can see evolution in one place Cons: Likely to clutter code, increase maintenance burden over time Support Plans for Versioning Need an SLA between service and consumers Need to define How long a consumer can depend on a version What constitutes end of life for a version Need to prepare for Extensions to end of life Presence of older clients Work with client to update to latest Assets to Create to Assist/Reduce Burden Documentation on wire-level formats XSD, HTML documents, sample code SDKs in client languages Java, Ruby, PHP, Python, .NET Can ease migration. Client uses new library, works till clean compile Versioning issue becomes deployment issue Support staff Dedicate staff to help support clients who are migrating code. Summary Versioning: The retrospective application of changes to a system. Plan ahead URL structure, version names, use MVC pattern Changes hit in three, related areas: Data, SOAP Methods, REST Manage changes Create new endpoints for new data types Use Data Transformation Objects Keep logic to translate between Data Transformation Objects and business in one place References\nVersioning Strategies by Microsoft\nBest Practices: Data Contract Versioning\nASP.NET Core RESTful Web API versioning made easy by Scott Hanselman\n","date":"22 February 2018","externalUrl":null,"permalink":"/versioning/","section":"Articles","summary":"In the article we are going to look at the importance of a good version control system, and why it is crucial when it comes to API versioning.\nIt is essential that we deploy a Web API version control from an early stage in our project. Versioning will ensure that the project is built on a solid base and that a standard is maintained. A good version control system will enable us to collaborate and scale in a managed way, and as such will provide our customers with a more straightforward progression through our upgrades.\n","title":"Versioning","type":"articles"},{"content":"","date":"22 February 2018","externalUrl":null,"permalink":"/categories/web-api/","section":"Categories","summary":"","title":"Web API","type":"categories"},{"content":"One thing I do like about MySQL is when using phpMyAdmin is the ability to search the whole database for any string, this should only be available for developers who are searching for data in an extensive database. It does take some time to run, but remember it has a lot to do.\nHere is the script that Narayana Vyas Kondreddi has produced which does the trick and works very well.\nCREATE PROC SearchAllTables ( @SearchStr nvarchar(100) ) AS BEGIN\n\u0026ndash; Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved. \u0026ndash; Purpose: To search all columns of all tables for a given search string \u0026ndash; Written by: Narayana Vyas Kondreddi \u0026ndash; Site: http://vyaskn.tripod.com \u0026ndash; Updated and tested by Tim Gaunt \u0026ndash; http://www.thesitedoctor.co.uk \u0026ndash; http://blogs.thesitedoctor.co.uk/tim/2010/02/19/Search+Every+Table+And+Field+In+A+SQL+Server+Database+Updated.aspx \u0026ndash; Tested on: SQL Server 7.0, SQL Server 2000, SQL Server 2005 and SQL Server 2010 \u0026ndash; Date modified: 03rd March 2011 19:00 GMT CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))\nSET NOCOUNT ON\nDECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110) SET @TableName = \u0026rsquo;' SET @SearchStr2 = QUOTENAME(\u0026rsquo;%\u0026rsquo; + @SearchStr + \u0026lsquo;%\u0026rsquo;,\u0026rsquo;\u0026rsquo;\u0026rsquo;\u0026rsquo;)\nWHILE @TableName IS NOT NULL\nBEGIN SET @ColumnName = \u0026rsquo;' SET @TableName = ( SELECT MIN(QUOTENAME(TABLE_SCHEMA) + \u0026lsquo;.\u0026rsquo; + QUOTENAME(TABLE_NAME)) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = \u0026lsquo;BASE TABLE\u0026rsquo; AND QUOTENAME(TABLE_SCHEMA) + \u0026lsquo;.\u0026rsquo; + QUOTENAME(TABLE_NAME) \u0026gt; @TableName AND OBJECTPROPERTY( OBJECT_ID( QUOTENAME(TABLE_SCHEMA) + \u0026lsquo;.\u0026rsquo; + QUOTENAME(TABLE_NAME) ), \u0026lsquo;IsMSShipped\u0026rsquo; ) = 0 )\nWHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)\nBEGIN SET @ColumnName = ( SELECT MIN(QUOTENAME(COLUMN_NAME)) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2) AND TABLE_NAME = PARSENAME(@TableName, 1) AND DATA_TYPE IN (\u0026lsquo;char\u0026rsquo;, \u0026lsquo;varchar\u0026rsquo;, \u0026rsquo;nchar\u0026rsquo;, \u0026rsquo;nvarchar\u0026rsquo;, \u0026lsquo;int\u0026rsquo;, \u0026lsquo;decimal\u0026rsquo;) AND QUOTENAME(COLUMN_NAME) \u0026gt; @ColumnName )\nIF @ColumnName IS NOT NULL\nBEGIN INSERT INTO #Results EXEC ( \u0026lsquo;SELECT \u0026rsquo;\u0026rsquo;\u0026rsquo; + @TableName + \u0026lsquo;.\u0026rsquo; + @ColumnName + \u0026lsquo;\u0026rsquo;\u0026rsquo;, LEFT(\u0026rsquo; + @ColumnName + \u0026lsquo;, 3630) FROM \u0026rsquo; + @TableName + \u0026rsquo; (NOLOCK) \u0026rsquo; + \u0026rsquo; WHERE \u0026rsquo; + @ColumnName + \u0026rsquo; LIKE \u0026rsquo; + @SearchStr2 ) END END END\nSELECT ColumnName, ColumnValue FROM #Results DROP TABLE #Results END Original post\n","date":"16 February 2018","externalUrl":null,"permalink":"/search-every-table-and-field-in-a-sql-server-database/","section":"Articles","summary":"One thing I do like about MySQL is when using phpMyAdmin is the ability to search the whole database for any string, this should only be available for developers who are searching for data in an extensive database. It does take some time to run, but remember it has a lot to do.\n","title":"Search every table and field in a SQL Server Database","type":"articles"},{"content":"Why, why, why I hear you say would you want to use Datasets with the Entity Framework?\nI’m not here to debate the whys and wherefores for doing this, just finding a simple solution to the problem.\n99.9% of the time I would say don’t, but if you have a legacy system and all the code is driven by DataSet’s you have many choices.\nRewrite all the business logic code to support EF Use an old style connection to the database Use DataSet’s via EF connection Each has their issues, the first could take some time, and would need full testing to ensure nothing had changed.\nUsing an old style database connection, you might as well just use the old legacy code.\nWhat I’m going to be covering here is being able to call a Stored Procedure using the Entity Framework and return a dataset, this way the legacy code remains the same but allow you to utilise the Entity Framework for your connection.\nLet’s get to work; first, we will create a Database Manager that will receive the Entity Framework DbContext\npublic class DatabaseManager { private readonly DbContext _context; public DatabaseManager(DbContext context) { _context = context; } }\nThen we need to call a Stored Procedure using the Entity Framework DbContext connection:\nnew SqlConnection(_context.Database.Connection.ConnectionString) I won’t go over creating the command with its parameters, as this is assumed you know how this works already. What I will mention is the SqlDataAdapter that calls the Stored Procedure and returns the DataSet\nusing (var adapter = new SqlDataAdapter(command)) { adapter.Fill(dataSet); } All you have to do now is return the dataSet and you are done. It is that easy, here is the full code base: DataSetEF\n","date":"31 January 2018","externalUrl":null,"permalink":"/datasets-with-entity-framework/","section":"Articles","summary":"Why, why, why I hear you say would you want to use Datasets with the Entity Framework?\nI’m not here to debate the whys and wherefores for doing this, just finding a simple solution to the problem.\n","title":"DataSets with Entity framework","type":"articles"},{"content":"","date":"31 January 2018","externalUrl":null,"permalink":"/categories/entityframework/","section":"Categories","summary":"","title":"EntityFramework","type":"categories"},{"content":"When solving a complex problem, it’s sometimes very tempting to choose an excellent solution. Not only will this solve the problem – but it will also impress your teammates and bring you everlasting glory.\nAn even better solution, however, would probably be a boring one. One that is easy to understand, even for your junior colleagues. One that is well-known for your platform and language. One that is entirely not extraordinary.\nUsing such a tedious solution means that you’re using simple vocabulary, which significantly increases the chances of everybody understanding you. This will make it a lot easier for everybody to follow along – including new team members (and yourself, a couple of weeks after you’ve written that code).\n","date":"19 January 2018","externalUrl":null,"permalink":"/choosing-the-boring-solution/","section":"Articles","summary":"When solving a complex problem, it’s sometimes very tempting to choose an excellent solution. Not only will this solve the problem – but it will also impress your teammates and bring you everlasting glory.\nAn even better solution, however, would probably be a boring one. One that is easy to understand, even for your junior colleagues. One that is well-known for your platform and language. One that is entirely not extraordinary.\n","title":"Choosing the Boring Solution","type":"articles"},{"content":"","date":"19 January 2018","externalUrl":null,"permalink":"/categories/development/","section":"Categories","summary":"","title":"Development","type":"categories"},{"content":"Acronyms FTW! Car enthusiasts might now think of BMW, but software developers should think of KISS and YAGNI.\n“Keep it simple, stupid” should remind us that the simple solution will always beat the overengineered solution. The reasons why this is true are almost endless. And they might be easier to understand when looking at the opposite: complex code.\nComplex code is a perfect hiding place for mistakes. Complex code is hard to understand, for your coworkers and yourself. Complex code cannot easily be extended. Complex code cannot be reused. And, last but certainly not least, writing complex code will cause your teammates to brand you as an outlaw.When a more straightforward solution seems sufficient right now, you should always aim for it. “Writing complex code will cause your teammates to brand you as an outlaw.”\nWhen you realise that your solution isn’t essential at all, you should drop it. This is what YAGNI is about – “You ain’t gonna need it” reminds us to stay modest when planning the volume and scope of our implementations. Will users need this feature? Will they need this option within a feature? These questions, of course, will translate to our code: will we need that class/ module/routine?\n","date":"19 January 2018","externalUrl":null,"permalink":"/aiming-for-simplicity/","section":"Articles","summary":"Acronyms FTW! Car enthusiasts might now think of BMW, but software developers should think of KISS and YAGNI.\n“Keep it simple, stupid” should remind us that the simple solution will always beat the overengineered solution. The reasons why this is true are almost endless. And they might be easier to understand when looking at the opposite: complex code.\n","title":"Aiming for Simplicity","type":"articles"},{"content":"Thank God for StackOverflow.com. I seriously can’t imagine my (programming) life without it. And with it being one of the most visited sites on the web, I guess I’m not alone.\nThere’s a long friendship between Stack Overflow and me. It helped me countless times when I was stuck on a problem. It gave me an idea of how other people had approached the same problem. Sometimes these other people helped me solve my problem. Sometimes they gave me a hint for a possible solution. And sometimes reading their issues at least let me know that I wasn’t alone with a miserable bug…\nAfter hours or even days of searching and trying different things, your shields are down. You are crawling through your code on all fours like a man who’s lost in the desert. But all of a sudden your search is fruitful! Eureka! Searching Stack Overflow has finally yielded a piece of code that works!\nThat’s when you have to watch out and resist the temptation to take code that works for the system that’s good. What you’ve found on Stack Overflow is – in all but the rarest cases – not a solution but rather a clue. It can certainly make for a great pointer, but it was not written with your exact problem/ requirements/ constraints/codebase/application in mind. And sometimes, it might just be a dirty hack.\nEmbrace Stack Overflow as a good source of guidance for specific problems. But also take the time to thoroughly and honestly evaluate if you’ve found a real, reliable solution.\n","date":"19 January 2018","externalUrl":null,"permalink":"/stack-overflow-driven-development/","section":"Articles","summary":"Thank God for StackOverflow.com. I seriously can’t imagine my (programming) life without it. And with it being one of the most visited sites on the web, I guess I’m not alone.\nThere’s a long friendship between Stack Overflow and me. It helped me countless times when I was stuck on a problem. It gave me an idea of how other people had approached the same problem. Sometimes these other people helped me solve my problem. Sometimes they gave me a hint for a possible solution. And sometimes reading their issues at least let me know that I wasn’t alone with a miserable bug…\n","title":"Stack-Overflow-Driven Development","type":"articles"},{"content":"Sometimes, a solution is so beautiful, and you wish you had the right problem to apply it to. But unfortunately, issues come first. As impressive as your new screwdriver may be (imagine a handle made of gold, with your initials engraved, of course, if the problem at hand is to knock in a nail, it makes for only a less than perfect solution.\nNow, after teaching you all I know about manual craft, let’s return to software development – and consider “design patterns” as your toolbox. Every design pattern you know (and understand) is an instrument in your toolbox. It’s certainly great to have many of them!\nThe problems start, however, as soon as you let the patterns dictate your coding. They should be there to support you, to propose a proven solution – for the right problem! Programming paradigms should be used where they fit and not be enforced. Your components should be designed with your application’s requirements in mind – not with a beautiful design pattern.\nIn cases where you’ve indeed found a helpful pattern for your current problem, there’s only one more thing: be sure to understand the pattern and its consequences on your coding.\n","date":"19 January 2018","externalUrl":null,"permalink":"/design-patterns/","section":"Articles","summary":"Sometimes, a solution is so beautiful, and you wish you had the right problem to apply it to. But unfortunately, issues come first. As impressive as your new screwdriver may be (imagine a handle made of gold, with your initials engraved, of course, if the problem at hand is to knock in a nail, it makes for only a less than perfect solution.\n","title":"Design Patterns","type":"articles"},{"content":"I’m sure you’ve used a third-party API at some point in your dev career – for example, to create new contacts in your CRM, to send emails through a newsletter service, or to do anything else with a third-party service virtually.\nIf you’ve interacted with a couple of such APIs, you will undoubtedly have noticed some differences between them: using one was probably more pleasant than the other. It’s easy to see which API was designed thoroughly, by an experienced developer, and perhaps with a lot of effort and thought. And it’s just as easy to be frustrated with an API that was designed poorly and sloppily. The former was probably a joy to use, while the latter was perhaps… not.\nSince the effects are so visible, most developers tend to quickly agree that it’s almost a duty to design public APIs in a careful and thought-out way. Nobody wants to work with a crappy API – and nobody wants to burden other developers with using their API being crappy.\nModern software design puts great emphasis on the concept of “application programming interfaces”. However, as most developers already know, the idea goes a lot deeper and is not exclusive to a public interface. Instead, you should build APIs inside your application, for internal use, too.\nApproaching these internal APIs in the same way you’d create a public one can make a huge difference: your colleagues (and you) will want to interact with this part of your application. Making the interaction as easy as possible for these people is one of the best goals you can have.\nA secure, thoughtful API is probably the part of your software where quality matters the most. Your colleagues might forgive you a little sloppiness in the internals of this or that method. But they won’t (and shouldn’t) forgive you for creating a dangerous API.\n","date":"19 January 2018","externalUrl":null,"permalink":"/creating-good-apis/","section":"Articles","summary":"I’m sure you’ve used a third-party API at some point in your dev career – for example, to create new contacts in your CRM, to send emails through a newsletter service, or to do anything else with a third-party service virtually.\n","title":"Creating Good APIs","type":"articles"},{"content":"Some differences between ASMX and WCF services are subtle and some differences between them are not subtle. The purpose of this section is to identify many of these differences and to provide guidance for how to handle them when preparing for, or when performing, migration. ASMX provides a very successful baseline for services, and WCF extends those capabilities for the next generation of services.\nThere are differences between ASMX and WCF, but it is important to also understand that WCF supports the same capabilities that ASMX provides. For example, you can use message types, XmlSerialization, custom SOAP headers, and Web Service Enhancements (WSE) in a WCF service. The remainder of this section describes some of these items; it also describes other areas that represent differences between ASMX and WCF.\nThe following subtopics describe the major differences between ASMX and WCF services:\nMessage Structure and Serialization SOAP Extensions Transport Protocols Security Exception Handling State Management Message Structure and Serialization Serialization is the process of translating binary objects into a data format that can be transmitted across process boundaries, computer boundaries, and network boundaries. When serialized data reaches the destination, or endpoint, it can be deserialized back into binary objects for use by an application. Both ASMX and WCF use SOAP for messages passed between two endpoints. However, for serialization, each uses different classes that implement different rules.\nASMX uses the XmlSerializer to translate classes into XML for communication, and to translate the XML back into classes on the receiver’s end. All public members are serialized unless they are marked as non-serializable using the XmlIgnoreAttribute. A large number of attributes can also be used to control the structure of the XML. For example, a property can be represented as an attribute using the XmlAttributeAttribute, or as an element using the XmlElementAttribute. The use of these attributes provides a great deal of control over how a type is serialized into XML; however, that power comes with an unfortunate downside. It may be possible to create XML structures that are not easily translated by other type systems, such as Java; XML structures that are not easily translated can hamper interoperability.\nWCF uses a DataContractSerializer to perform the same translation; however, the behavior is different from the XmlSerializer. The XmlSerializer uses an implicit model where all public properties are serialized unless they are marked with the XmlIgnoreAttribute, but the DataContractSerializer uses an explicit model where the properties and/or fields that you want to serialize must be marked with a DataMemberAttribute. It is important to note that WCF can also use the XmlSerializer to perform serialization operations.\nA notable difference between ASMX and WCF is the WCF ability to serialize class members regardless of the access specifier used. This means it is now possible to serialize private fields. Using this capability, you can encapsulate fields in a data type. For example, you can provide read-only access to a private field by implementing only the get method on a property. You can then serialize that private field by adding the DataMember attribute to the field in a WCF service.\nAnother important difference is that the DataContractSerializer generates a simplified XML structure that increases its ability to interoperate between different operating systems. In addition, the ability for users to control the XML structure is limited. This simplified structure also means that future versions of WCF will be able to target this structure for optimization. Finally, in comparison to the XmlSerializer, the serialization of data is greatly improved with the DataContractSerializer.\nRecommendation Using WCF, you can use the XmlSerializer for types that are already created. However, to maximize interoperability, it is recommended to use WCF data contracts and the DataContractSerializer. The Web Service Software Factory (ASMX) guidance package, also referred to as the ASMX guidance package, creates types that should also migrate to WCF data contracts if no additional XML serialization attributes, such as XmlAttributeAttribute, are added. The ASMX guidance package includes an XmlNamespaceAttribute to specify the namespace of the types.\nSOAP Extensions Developers can use the SOAP extensions feature of ASP.NET to interact directly with SOAP messages. By using SOAP extensions, you can intercept the SOAP message and insert your own code into the SOAP message pipeline, which allows you to extend the capabilities of SOAP. For example, features such as security, transaction management, routing, and tracing can be implemented by using SOAP extensions. The downside of this capability is that it reduces the SOAP message’s ability to interoperate with other operating systems. In other words, other operating systems may not be able to handle a SOAP message that has been customized.\nWCF does not support the use of SOAP extensions, but it does have other extensibility points that can be used to intercept and manipulate SOAP messages. For example, you can use a behavior extension to hook into the WCF Dispatcher with a class that implements IDispatchMessageInspector.\nRecommendation Avoid the use of SOAP extensions when developing new ASMX services that will be migrated to WCF unless you are willing to rewrite them or if you are confident that WCF provides a similar capability.\nTransport Protocols ASMX services use the HTTP transport protocol for communications with Internet Information Services (IIS) as the host. An ASMX service file has the file name extension .asmx, which is accessed using a Uniform Resource Locator (URL); for example, http://localhost/ASMXEmployee/EmployeeManager.asmx.\nWCF services can also use the HTTP protocol, but unlike ASMX services, you also have the option to use other transport protocols. The following protocols are supported by WCF:\nHypertext Transfer Protocol (HTTP) Transmission Control Protocol (TCP) Message Queuing (also known as MSMQ) Named pipes Many different hosts can also be used with WCF services. For example, IIS can be used as a host with the HTTP transport protocol. Windows services and stand-alone applications can be used as a host for other transport protocols.\nAccessing a service hosted in IIS is similar to accessing an ASMX service; for example, http://localhost/WCFEmployee/EmployeeManager.svc.\nThe only difference between the two services is the file name extension. However, you can also configure a WCF service to use the .asmx file name extension, as described in the Service Configuration topic. WCF services that use other transport protocols are accessed using methods associated with the specific protocol.\nWhen migrating an ASMX service to WCF, the protocol you choose is based on the client applications that will be accessing the service. If you need to support ASMX client applications, you also need to use the HTTP protocol. In addition, when configuring a WCF service for ASMX client applications, you need to configure the service to use BasicHttpBinding, as described in the Service Configuration topic.\nRecommendation When migrating services from ASMX to WCF, and if ASMX client applications need to access the migrated service, use the HTTP protocol and configure the new service to use BasicHttpBinding.\nSecurity Typically, authentication and authorization with ASMX is done using IIS and ASP.NET security configurations and transport layer security. In addition, Web Service Extensions (WSE) can be used to provide additional security capabilities, such as message layer security.\nWCF can use the same security components as ASMX, such as transport layer security and WSE. However, WCF also has its own built-in security, which allows for a consistent security programming model for any transport. The security implemented by WCF supports many of the same capabilities as IIS and WS-* security protocols. However, when using IIS, you must also enable anonymous access to the service so that WCF security is implemented.\nA powerful reason for migrating an ASMX service to WCF is to take advantage of new security capabilities that are provided by WCF. For example, WCF provides support for claims-based authorization that provides finer-grained control over resources than role-based security. In addition, instead of depending on a transport protocol such as HTTP and extensions such as WSE, security is built into WCF. The end result is that security is consistent regardless of the host that is used to implement a WCF service.\nRecommendation When possible, migrate both client applications and services to WCF to take advantage of the new security features that are available with WCF. Use of the WCF Security guidance package is also recommended when configuring security for WCF services and client applications.\nIf a migrated WCF service must support ASMX client applications, you can use transport security associated with HTTP and HTTPS. You can also use WSE 3.0, but you must configure a custom WCF binding for this to work. For additional information about using WSE 3.0 with WCF, see Interoperating with WSE Sample on MSDN.\nException Handling With ASMX services, unhandled exceptions are always returned to client applications as SOAP faults. An ASMX service can also throw the SoapException class, which provides more control over the content of the SOAP fault that is returned to the client application.\nHowever, when an unhandled exception occurs, the default configuration of WCF protects sensitive data from exposure by not returning sensitive information in SOAP fault messages. You can override this behavior by adding a serviceDebug element to the service behavior in the configuration file that is associated with a WCF service. Overriding this behavior is not recommended for deployment; it should be used only in a development environment.\nSimilar to the SoapException class used with ASMX services, you can also throw a custom exception by using the FaultException\u0026lt;T\u0026gt; type, where T is a data contract that contains the exception information. The use of custom exceptions also requires the declaration of a FaultContract on operations that will throw the exception.\nThe following code example demonstrates how a DataContract is used to define a FaultContract declared on a service operation in a ServiceContract.\nC# [DataContract] public class FindEmployeeFault { [DataMember] public string Request; [DataMember] public string Description; } [ServiceContract] public interface IEmployeeManager { [OperationContract(Action = \u0026ldquo;FindEmployeeByLastName\u0026rdquo;)] [FaultContract(typeof(EmployeeService.FaultContracts.FindEmployeeFault))] EmployeeService.DataContracts.Employee FindEmployeeByLastName(string request); }\nThis next code example demonstrates how to catch a FaultException that may be thrown by the service operation shown in the preceding code example.\nC# // client function used to find an employee public Employee FindEmployee( string lastName ) { Employee employee = null; try { employee = proxy.FindEmployeeByLastName( lastName ); } catch( FaultException\u0026lt;FindEmployeeFault\u0026gt; ex ) { Console.WriteLine(\"FaultException\u0026lt;FindEmployeeFault\u0026gt;: While finding \" + ex.Detail.Request + \". Because: \" + ex.Detail.Description ); } return employee; } The filtering of exception data that is returned from a service is described using an Exception Shielding pattern. The pattern describes how exception handlers can be used to filter the data that is returned to a client application. To help facilitate the creation of exception handlers in WCF services, the Service Factory: Modeling Edition includes the Data Contract Model that contains a fault contract shape that you can use to create WCF fault contracts.\nRecommendation WCF provides exception shielding, but you should always define exception handlers for both ASMX and WCF services. For more information, see Exception Handling in Service Oriented Applications.\nState Management ASMX services have access to the HttpContext class, which provides access to state managers with a different scope, such as application scope and session scope. ASP.NET also provides control over how state data is managed. Consequently, you should minimize the use of state in a service because of the effect it has on the scalability of an application.\nWCF provides extensible objects that can be used for state management. Extensible objects implement the System.ServiceModel.IExtensibleObject\u0026lt;T\u0026gt; interface. The two main classes that implement the IExtensibleObject interface are ServiceHostBasedand InstanceContext. The ServiceHostBased class provides the ability for all service instances in the same host to access the same state data. On the other hand, the InstanceContext class only allows access to state data within the same service instance.\nTo implement state management in WCF, you need to define a class that implements the IExtension interface, which is used to hold the state data. Instances of this class can then be added to one of the IExtensibleObject classes using the Extensions property. The following code example shows how to implement state using the InstanceContext.\nC# internal class StateData: IExtension\u0026lt;InstanceContext\u0026gt; { public string Identifier = string.Empty; public string Data = string.Empty; public StateData( string data ) { Identifier = Guid.NewGuid().ToString(); Data = data; } }\npublic string AddStateData( string data ) { StateData state = new StateData( data ); OperationContext.Current.InstanceContext.Extensions.Add(state); return state.Identifier; }\npublic string GetStateData( string identifier ) { Collection\u0026lt;StateData\u0026gt; dataCollection = OperationContext.Current.InstanceContext.Extensions.FindAll\u0026lt;StateData\u0026gt;();\nstring result = string.Empty; foreach( StateData data in dataCollection ) { if( data.Identifier == identifier ) { Result = data.Data; break; } } return result; }\nRecommendation The ability to control where state is maintained in WCF is much more limited than in ASP.NET. As a result, state management is commonly used as the primary reason for enabling the ASP.NET compatibility mode, which provides access to ASP.NET components; this means you have much more control over where state is maintained. For example, when a service is configured for ASP.NET compatibility, you have access to HTTP context classes that provide the same functionality as the ASMX implementation.\nWhen developing new ASMX services, you should avoid the use of state in your services; all services should be stateless.\nOriginal source from Microsoft, edited and moved here as the content on Microsoft was in fear of being removed.\n","date":"16 January 2018","externalUrl":null,"permalink":"/differences-between-asmx-and-wcf-services/","section":"Articles","summary":"Some differences between ASMX and WCF services are subtle and some differences between them are not subtle. The purpose of this section is to identify many of these differences and to provide guidance for how to handle them when preparing for, or when performing, migration. ASMX provides a very successful baseline for services, and WCF extends those capabilities for the next generation of services.\n","title":"Differences Between ASMX and WCF Services","type":"articles"},{"content":"","date":"16 January 2018","externalUrl":null,"permalink":"/categories/wcf/","section":"Categories","summary":"","title":"WCF","type":"categories"},{"content":"","date":"10 January 2018","externalUrl":null,"permalink":"/categories/attributes/","section":"Categories","summary":"","title":"Attributes","type":"categories"},{"content":"Attributes are advantageous in C# to provide none business-related functionality in an application or to abstract out the code to make it easier to follow.\nThe issue is when does the attribute code get called and how do you force it to run?\nI set the task on to write a simple console application showing different ways you can use attributes.\nI found a fascinating article for my first sample application on Defining and Using Custom Attribute Class in C# by David Tansey, below is an edited version of this article:\nThe complex, component-style development that businesses expect out of modern software developers requires greater design flexibility than the design methodologies of the past.\nMicrosoft’s .NET Framework makes extensive use of attributes to provide added functionality through what is known as “declarative” programming. Attributes enhance flexibility in software systems because they promote loose coupling of functionality. Because you can create your custom attribute classes and then act upon them, you can leverage the loose coupling power of attributes for your purposes.\nThe .NET Framework makes many aspects of Windows programming much more straightforward. In many cases, the Framework’s use of metadata that .NET compilers bind to assemblies at compile time causes tricky programming easier. Indeed, the use of intrinsic metadata makes it possible for .NET to relieve us from “DLL Hell.”\nLucky for us, the designers of the .NET framework did not choose to keep these metadata “goodies” hidden away under the covers. The designers gave us the Reflection API through which a .NET application can programmatically investigate this metadata. An application can “reflect” upon any imaginable aspect of a given assembly or on its contained types and their members.\nBinding the metadata to the executable provides many advantages. It makes the assemblies in .NET fully self-describing. This allows developers to share components across languages and eliminates the need for header files. (They can become out-of-date relative to the implementation code.)\nWith all this positive news about .NET metadata, it seems hard to believe there could be anything more to the story? But there is. You can create your application-specific metadata in .NET and then use that metadata for any purpose you can imagine.\nDevelopers define their application-specific metadata through the use of Custom Attributes. Because these attribute values become just another part of the metadata bound into an assembly, the custom attribute values are available for examination by the Reflection API.\nIn this article, you’ll learn how to define custom attribute classes, how to apply attributes to classes and methods in your source code, and you’ll learn how to use the Reflection API to retrieve and act upon these values.\nHow Does .NET Use Attributes in the Common Language Runtime? Before you start to consider what you can accomplish with your custom attribute classes, let’s examine some of the standard attributes that the Common Language Runtime already makes available.\nThe [WebService] attribute provides a simple example? It lets you turn any public method of a WebService subclass into a method that you can expose as part of the Web Service merely by attaching the [WebMethod] attribute to the method definition.\npublic class SomeWebService : System.Web.Services.WebService { [WebMethod] public DataSet GetDailySales( ) { // code to process the request\u0026hellip; } }\nYou just attach the [WebMethod] attribute to the method, and .NET handles everything else for you behind the scenes.\nUsing the [Conditional] attribute allows you to make a given method conditional based on the presence or absence of the specified preprocessing symbol. For example, the following code:\npublic class SomeClass { [Conditional( \"DEBUG\" )] public void UnitTest( ) { // code to do unit testing... } } Indicates that the UnitTest( ) method of this class is “conditional” based on the presence of the preprocessing symbol “DEBUG”. The fascinating part is what happens. The compiler stubs out all calls to the method when the condition fails rather than attempt to nullify the behaviour of the method the way an #if…#endif pre-processing directive does. This is a much cleaner approach, and again we didn’t have to do much of anything to utilise this functionality.\nAttributes utilise positional and/or named parameters. In the example using the [Conditional] attribute, the symbol specification is a positional parameter. You must always supply positional parameters.\nTo look at named parameters, let’s return to the [WebMethod] attribute example. This attribute has a named parameter called Description. To use it you would change the line to read:\n[WebMethod(Description = \"Sales volume\" )] Named parameters are optional, and you write them using the name of the parameter followed by the assignment of a value. Named parameters follow after you’ve specified all positional parameters.\nI will talk more about named and positional parameters later in this article when I show you how to create and apply your Attribute class.\nRun-Time, Design-Time The examples provided in this article are involved in run-time activities. But Binaries (assemblies) aren’t just for run-time. In .NET, the metadata you describe isn’t limited to being available only at runtime. You can query the metadata at any time after you’ve compiled an assembly.\nThink about some design-time possibilities. The open nature of the IDE in Visual Studio.NET allows you to create tools (using .NET languages) that facilitate development and design (wizards, builders, etc.) Thus, one module’s run-time environment (the IDE tool) is another module’s design-time environment (the source code being developed). This presents an excellent opportunity to implement some custom attributes. You could allow the IDE tool to reflect and then act upon the source classes/types you develop. Unfortunately, due to the additional subject of the IDE tool code, exploring such an example is beyond the scope of a single article.\nThe standard .NET attributes contain a similar example. When a developer creates custom controls to include in the Toolbox of the Visual Studio .NET IDE, they have attributes available to them to indicate how to handle the control in the property sheet. Table 1 lists and describes the four standard .NET attributes that the property sheet uses.\nThese property sheet-related attributes make it clear that you can use attributes and their values in the design-time as well as in the run-time environment.\nCustom Attributes vs. Class Properties Apparent similarities exist between attributes and regular member properties of a class. This can make it difficult to decide when and where you might want to utilise a custom attribute class. Developers commonly refer to properties of a class and their values as being “attributes” themselves, so what is the difference between properties and attributes?\nAn attribute takes the same “shape and form” as a property when you define it, but you can attach it to all manner of different assembly level types?not just Classes. Table 2 lists all the assembly level types that you can apply attributes.\nLet’s pick one item from the list as an example. You can apply an attribute to a parameter, which is a little bit like adding a property to a parameter? A very novel and powerful idea indeed, because you just can’t do that with class member properties. This emphasises the most significant way in which attributes and properties are different because properties are just always going to be members of a class? They can’t be associated with a parameter or any number of other types listed in Table 2 different than Class.\nMember properties of a class are also limited in another way in which attributes are not. By definition, a member property is tied to a specific class. That member property can only ever be used through an instance or subclass instance of the class on which the property was defined. On the other hand, you can attach/apply attributes anywhere! The only requirement is that the assembly type the attribute is being assigned to matches the validon definition in the custom attribute. We’ll talk more about the validon property of custom attribute classes in the next section. This characteristic of attributes helps to promote the loose coupling that is so helpful in component-style development.\nAnother difference between properties and attributes relates to the values you can store in each of them. The values of member properties are instance values and can be changed at run-time. However, in the case of attributes, you set values at design time (in source code) and then compile the attributes (and their values) directly into the metadata contained in an assembly. After that point you cannot change the values of the attributes?you’ve essentially turned the values of the attributes into hard-coded, read-only data.\nConsider this when you attach an attribute. If you attach an attribute to a class definition, for example, every instance of the class will have the same values assigned to the attribute regardless of how many objects of this class type you instantiate. You cannot attach an attribute to an instance of a class. You may only attach an attribute to a Type/Class definition.\nCreating a Custom Attribute Class Now we’ll create a more realistic implementation of the ideas presented above. Let’s create a custom attribute class. This will allow us to store some tracking information about code modifications that you would typically record as comments in source code. For example, we’ll mark just a few items: defect id, developer id, the date of the change, the origin of the defect, and a comment about the fix. To keep the example simple we’ll focus on creating a custom attribute class (DefectTrackAttribute) designated for use only with classes and methods.\nListing 1 shows the source code for the DefectTrackAttribute class. You can identify some critical lines of code.\nIf you haven’t used attributes before, the following line of code might look a bit strange.\n[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] This line attaches an [AttributeUsage] attribute to the attribute class definition. Square bracket syntax identifies the construct as an attribute. So, Attributes classes can have their attributes. This may seem a bit confusing at first, but it should become more evident as we show you what you’ll use it for.\nThe [AttributeUsage] attribute has one positional parameter and two named parameters. The positional parameter validon specifies which of the various assembly types you can attach this attribute to. The value for this parameter uses a combination of values from the AttributeTargets enumeration. In my example, I allow only classes and methods, so I get the proper specification by OR’ing the two AttributeTargets values together.\nThe first named parameter of the [AttributeUsage] attribute (and the only one specified in the example) is the AllowMultiple parameter, which indicates whether you can apply this type of attribute multiple times to the same category. The default value is false. However, you want to use the AllowMultiple parameter of the Attribute more than once on a single type because that represents what the example will model. A given method or class potentially goes through many revisions during its lifetime, and you need to be able to denote each of these changes with an individual [DefectTrack] attribute.\nThe second named parameter of the [AttributeUsage] attribute is the Inherited parameter, which indicates whether or not derived classes inherit the attribute. I’ve made the default value for this parameter false. I opted to take the default value, so I did not specify this named parameter. Why? The source code modification information I want to capture is always related to each class and method individually. Would it confuse the developer for a class to inherit the [DefectTrack] attribute(s) from its parent class? The developer couldn’t distinguish which [DefectTrack] attributes came from the parent and which were specified directly.\nListing1 then lists the class declaration. Attribute classed are subclassed from System.Attribute. You will directly or indirectly subclass all custom Attribute classes from System.Attribute.\nNext, Listing 1 shows that I’ve defined five private fields to hold the values for the attribute.\nThe first method in our Attribute class is the class constructor, which has a call signature with three parameters. The parameters of a constructor for an Attribute class represent the positional parameters for that attribute, which makes these required parameters. If you choose, you can create overloaded constructors and have more than one proper positional / configuration of parameter needed.\nThe remainder of the Attribute class is a series of public property declarations that correspond to the private fields of the class. You’ll use these properties to access the values of the attribute when you get to the example that examines the metadata. Note that the properties that correspond to the positional parameters only have a get clause and do not have a set clause. This makes these properties read-only and communicates with the fact that these are meant to be positional and not named parameters.\nApplying the Custom Attribute You’ve already seen that you can attach an attribute to a target item in your C# code by putting the attribute name and its parameters in square brackets immediately before the item’s declaration statement.\nIn Listing 2 you attach the [DefectTrack] attribute to a couple of methods and a couple of classes.\nYou need to ensure that you have access to the class definition for your custom attribute, so you start by including this line.\nusing MyAttributeClasses; Beyond that, you’re merely “adorning” or “decorating” your class declarations and some of your methods with the [DefectTrack] custom attribute.\nSomeCustomPricingClass has two uses of the [DefectTrack] attribute attached. The first [DefectTrack] attribute uses only the three positional parameters whereas the second [DefectTrack] attribute also includes a specification for the named parameter Origin.\n[DefectTrack( \"1377\", \"12/15/02\", \"David Tansey\" ) ] [DefectTrack( \"1363\", \"12/12/02\", \"Toni Feltman\", Origin = \"Coding: Unhandled Exception\")] public class SomeCustomPricingClass { ... } The PriceIsValid( ) method also uses the [DefectTrack] custom attribute, and it includes a specification for both of the named parameters, Origin and FixComment. Listing 2 contains a couple of additional uses of the [DefectTrack] attribute that you can examine on you own.\nSome readers might wonder if you could rely on the old-fashioned approach of using comments for this sort of source modification information. .NET does make tools available for using XML blocks within comments to give them some structure and form.\nYou can easily see a comment in your source code right at the relevant place. You could process such information by text parsing the comments in the source, but it’s tedious and potentially error-prone. .NET provides tools to process XML blocks in comments that practically eliminate this issue.\nUsing a custom attribute for the same purpose also provides you with a structured approach to recording and processing the information, but it has an added advantage. Consider that after you compile source code into a binary, you lose your comments?forever removed from the byproduct executable code. By comparison, the values of the attributes become a part of the metadata that you’ve permanently bound to the assembly?you have still had access to the information even without any source code.\nAdditionally, the way an attribute “reads” in source code allows it to fill the same valuable design-time function still that the original comment did.\nRetrieving the Values of the Custom Attributes At this point, even though you’ve applied your custom attribute to some classes and methods, you haven’t seen it in action. It seems as if nothing indeed occurs whether you attach the attributes or not. But something does happen and you don’t have to take my word for it. You can use the MSIL Disassembler to open an EXE or DLL that contains types you’ve decorated with your custom attributes. The MSIL Disassembler lets you see that .NET included your attributes and their values right there in the IL code. Figure 1 shows an example of ILDASM form with the EXE from the sample code in this article opened.\nDespite seeing the attribute values in the disassembly as proof of their existence, you still haven’t seen any action related to them. Now you’ll use the Reflection API to traverse the types/objects of an assembly, query for your custom attribute, and retrieve the attribute values when you find types that have your custom attribute attached to them.\nConsider the general structure and intent of the test program in Listing 3. The program loads the specified assembly, gets an array of all members of the assembly, and iterates through each member looking for classes that have the [DefectTrack] attribute attached. For classes that have the attribute, the test program outputs the values of the attribute to the console. The program then performs the same steps and iteration for methods. These loops “walk” their way through the entire assembly.\nNow examine some of the more critical lines of code. The first line and second line of the DisplayDefectTrack( ) method retrieve a reference to an Assembly object by loading the specified Assembly and then extracts an array containing all of the types in the assembly.\nAssembly loAssembly = Assembly.Load( lcAssembly ) ; Type[ ] laTypes = loAssembly.GetTypes( ) ; A FOR…EACH loop iterates through each of the types of the assembly. The program outputs the name of the current type to the console, and then the following line of code queries the present type for an array containing [DefectTrack] attributes.\nobject[ ] laAttributes = loType.GetCustomAttributes(typeof(DefectTrackAttribute ), false ) ; You specify the parameter typeof(DefectTrackingAttribute) on the GetCustomAttributes() method so that you can limit the returned custom attributes to be only of the type that you created in the example. The second parameter of false indicates that you do not want to include the type’s inheritance chain when trying to find your attributes.\nA FOR…EACH loop iterates through each of the custom attributes and outputs its values to the console. You should recognise that the first line of the FOR…EACH block creates a new variable and does a typecast against the current attribute.\nDefectTrackAttribute loDefectTrack = (DefectTrackAttribute)loAtt ; Why is this necessary? The GetCustomAttributes() method returned an array that contains references that get cast to the generic type Object. You want to gain access to the values from your custom attribute class, and to do so, you must recast these references to their actual concrete type, DefectTrackAttribute. Once you’ve completed this, you can use the attributes, and the program can output the attribute values to the console.\nBecause you can apply your attribute to either classes or methods, the program then calls the GetMethods() method of the current type object from the assembly.\nMethodInfo[ ] laMethods = loType.GetMethods( BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly ) ; For example, we have chosen to pass some values from the BindingFlags enumeration to GetMethods(). These three BindingFlags, when used in combination, limit the methods returned to ones that you defined directly in the current class. I wanted to limit the amount of output in the example, but you probably would not do this in practice because a developer might apply the [DefectTrackAttribute] to an overridden method. My implementation would not catch those attributes.\nThe remaining code does virtually the same processing for each of the methods that it did for each of the classes? The code queries each method for custom attributes of the [DefectTrack] type and then outputs the values for the ones it finds to the console.\nConclusion This is just presented the implementation as only one example of how a developer might use .NET attributes to enhance their development process. Custom attributes are a bit like XML in that the significant benefits aren’t related to “what it does.” Custom attributes’ real interests lie in “what you can do with it.” The possibilities are truly limitless, and the open nature of custom attributes makes it likely that some of their most novel and powerful uses have yet to be conceived of.\nListing 1: Custom attribute class for DefectTrack attribute\nusing System; namespace DefiningAndUsingCustomAttribute { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public class DefectTrackAttribute : System.Attribute { private string cDefectID; private DateTime dModificationDate; private string cDeveloperID; private string cDefectOrigin; private string cFixComment;\npublic DefectTrackAttribute(string lcDefectID, string lcModificationDate, string lcDeveloperID) { this.cDefectID = lcDefectID; this.dModificationDate = System.DateTime.Parse(lcModificationDate); this.cDeveloperID = lcDeveloperID; }\npublic string DefectID { get { return cDefectID; } }\npublic DateTime ModificationDate { get { return dModificationDate; } }\npublic string DeveloperID { get { return cDeveloperID; } }\npublic string Origin { get { return cDefectOrigin; } set { cDefectOrigin = value; } }\npublic string FixComment { get { return cFixComment; } set { cFixComment = value; } } } }\nListing 2: Two example classes with attributes attached\nnamespace DefiningAndUsingCustomAttribute { [DefectTrack(\"1377\", \"12/15/02\", \"David Tansey\")] [DefectTrack(\"1363\", \"12/12/02\", \"Toni Feltman\", Origin = \"Coding: Unhandled Exception\")] public class SomeCustomPricingClass { public double GetAdjustedPrice(double tnPrice, double tnPctAdjust) { return tnPrice + (tnPrice * tnPctAdjust); } [DefectTrack(\u0026ldquo;1351\u0026rdquo;, \u0026ldquo;12/10/02\u0026rdquo;, \u0026ldquo;David Tansey\u0026rdquo;, Origin = \u0026ldquo;Specification: Missing Requirement\u0026rdquo;, FixComment = \u0026ldquo;Added PriceIsValid( ) function\u0026rdquo;)] public bool PriceIsValid(double tnPrice) { return tnPrice \u0026gt; 0.00 \u0026amp;\u0026amp; tnPrice \u0026lt; 1000.00; } } }\nListing 3: Code to walk assembly and output attribute values\nusing System; using System.Reflection; namespace DefiningAndUsingCustomAttribute { public class TestMyAttribute { public static void Main() { DisplayDefectTrack(\u0026ldquo;DefiningAndUsingCustomAttribute\u0026rdquo;); Console.ReadLine(); }\npublic static void DisplayDefectTrack( string lcAssembly) { Assembly loAssembly = Assembly.Load(lcAssembly);\nType[] laTypes = loAssembly.GetTypes();\nforeach (Type loType in laTypes) { Console.WriteLine(\u0026quot;======================\u0026quot;); Console.WriteLine(\u0026ldquo;TYPE:\\t\u0026rdquo; + loType.ToString()); Console.WriteLine(\u0026quot;=====================\u0026quot;);\nobject[] laAttributes = loType.GetCustomAttributes(typeof(DefectTrackAttribute), false);\nif (laAttributes.Length \u0026gt; 0) Console.WriteLine(\u0026quot;\\nMod/Fix Log:\u0026quot;);\nforeach (Attribute loAtt in laAttributes) { DefectTrackAttribute loDefectTrack = (DefectTrackAttribute)loAtt;\nConsole.WriteLine(\u0026quot;\u0026mdash;\u0026mdash;\u0026mdash;\u0026mdash;\u0026mdash;\u0026mdash;\u0026mdash;-\u0026quot;); Console.WriteLine(\u0026ldquo;Defect ID:\\t\u0026rdquo; + loDefectTrack.DefectID); Console.WriteLine(\u0026ldquo;Date:\\t\\t\u0026rdquo; + loDefectTrack.ModificationDate); Console.WriteLine(\u0026ldquo;Developer ID:\\t\u0026rdquo; + loDefectTrack.DeveloperID); Console.WriteLine(\u0026ldquo;Origin:\\t\\t\u0026rdquo; + loDefectTrack.Origin); Console.WriteLine(\u0026ldquo;Comment:\\n\u0026rdquo; + loDefectTrack.FixComment); }\nMethodInfo[] laMethods = loType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);\nif (laMethods.Length \u0026gt; 0) { Console.WriteLine(\u0026quot;\\nMethods: \u0026ldquo;); Console.WriteLine(\u0026rdquo;\u0026mdash;\u0026mdash;\u0026mdash;\u0026mdash;\u0026mdash;\u0026mdash;\u0026mdash;-\u0026quot;); }\nforeach (MethodInfo loMethod in laMethods) { Console.WriteLine(\u0026quot;\\n\\t\u0026quot; + loMethod.ToString());\nobject[] laMethodAttributes = loMethod.GetCustomAttributes(typeof(DefectTrackAttribute), false);\nif (laMethodAttributes.Length \u0026gt; 0) Console.WriteLine(\u0026quot;\\n\\t\\tMod/Fix Log:\u0026quot;);\nforeach (Attribute loAtt in laMethodAttributes) { DefectTrackAttribute loDefectTrack = (DefectTrackAttribute)loAtt; Console.WriteLine(\u0026quot;\\t\\t\u0026mdash;\u0026mdash;\u0026mdash;\u0026mdash;\u0026mdash;-\u0026quot;); Console.WriteLine(\u0026quot;\\t\\tDefect ID:\\t\u0026quot; + loDefectTrack.DefectID); Console.WriteLine(\u0026quot;\\t\\tDeveloper ID:\\t\u0026quot; + loDefectTrack.DeveloperID); Console.WriteLine(\u0026quot;\\t\\tOrigin:\\t\\t\u0026quot; + loDefectTrack.Origin); Console.WriteLine(\u0026quot;\\t\\tComment:\\n\\t\\t\u0026quot; + loDefectTrack.FixComment); } } Console.WriteLine(\u0026quot;\\n\\n\u0026quot;); } } } }\nTable 1: Standard .NET attributes that the property sheet uses at design-time in the Visual Studio .NET IDE. Attribute Description Designer Specifies the class used to implement design-time services for a component. DefaultProperty Specifies which property to indicate as the default property for a component in the property sheet. Category Specifies the category in which the property will be displayed in the property sheet. Description Specifies the description to display in the property sheet for a property. Table 2: .NET assembly level types that you can apply attributes to. Type Assembly Class Delegate Enum Event Interface Method Module Parameter Constructor Field Property ReturnValue Structure DefiningAndUsingCustomAttribute.zip\n","date":"10 January 2018","externalUrl":null,"permalink":"/defining-and-using-custom-attribute-classes-in-c/","section":"Articles","summary":"Attributes are advantageous in C# to provide none business-related functionality in an application or to abstract out the code to make it easier to follow.\nThe issue is when does the attribute code get called and how do you force it to run?\n","title":"Defining and Using Custom Attribute Classes in C#","type":"articles"},{"content":"","date":"22 November 2017","externalUrl":null,"permalink":"/categories/gdpr/","section":"Categories","summary":"","title":"GDPR","type":"categories"},{"content":"A quick list for GDPR Compliance\nDo you have a contact form? Make sure you add a checkbox explicitly asking the user for the form if they consent to you storing and using their personal information to get back in touch with them. The box must be unchecked by default. Also, mention if you will send or share the data with any 3rd-parties and which.\nCan visitors comment anywhere on your website? Make sure you add a checkbox explicitly asking the user of the comment section if they consent to store their message attached to the e-mail address they’ve used to comment. The box must be unchecked by default. Also, mention if you will send or share the data with any 3rd-parties and which. Is there an order form on your website or webshop present? Make sure you add a checkbox explicitly asking the user of the form if they consent to you storing and using their personal information to ship the order. This cannot be the same checkbox as the Privacy Policy checkbox you should already have in place. The box must be unchecked by default. Also, mention if you will send or share the data with any 3rd-parties and which. Do you provide a forum or message board environment? Make sure you add a checkbox explicitly asking forum/board users if they consent to you storing and using their personal information and messages. The box must be unchecked by default. Also, mention if you will send or share the data with any 3rd-parties and which. Can visitors chat with your company directly? Make sure you add a checkbox explicitly asking chat users if they consent to you storing and using their personal information and messages. The box must be unchecked by default. We recommend also mentioning for how long you will save chat messages or deleting them all within 24 hours. Also, mention if you will send or share the data with any 3rd-parties and which. ","date":"22 November 2017","externalUrl":null,"permalink":"/gdpr-compliance-checklist/","section":"Articles","summary":"A quick list for GDPR Compliance\nDo you have a contact form? Make sure you add a checkbox explicitly asking the user for the form if they consent to you storing and using their personal information to get back in touch with them. The box must be unchecked by default. Also, mention if you will send or share the data with any 3rd-parties and which.\n","title":"GDPR Compliance Checklist","type":"articles"},{"content":"On 25th May 2018, the GDPR (General Data Protection Regulation) enacted by the EU will come into effect.\nHow do you make your website GDPR compliant? What are the steps that you must take to ensure that you follow the guidelines? What if you neglect this? This article will help you in your endeavour to be ready when the regulation kicks in.\nFirst, we’re going to talk in detail about the GDPR guidelines, the specific areas of your business that the guidelines affect, and why you should be concerned about your website and GDPR compliance. Next, we will cover the basics of making a website site compliant with the guidelines. Finally, we will discuss the implications of the use of tools on your website and how your GDPR compliance might be affected. What is GDPR? Disclaimer. This post is not legal advice. I am not lawyer. GDPR stands for General Data Protection Regulation, and it is a new data protection law in the EU, which comes into force in May 2018. The GDPR aims to give citizens of the EU control over their data and change the approach of organisations across the world towards data privacy.\nThe GDPR provides much stronger rules than existing laws and is much more restrictive than the “EU cookie law.”\nFor instance, users must confirm that their data can be collected, there must a clear privacy policy showing what data is going to be stored, how it is going to be used, and provide the user with a right to withdraw the consent to the use of personal data (consequently deleting the data), if required.\nThe GDPR law applies to data collected about EU citizens from anywhere in the world. As a consequence, a website with any EU visitors or customers must comply with the GDPR, which means that virtually all sites and businesses must meet.\nTo better understand the regulation, take a look at the publication of the rules in the Official Journal of the European Union, which defines all terms related to the law. There are two main aspects of the GDPR: “personal data” and “processing of personal data.” Here’s how it relates to running a website:\npersonal data pertains to “any information relating to an identified or identifiable natural person” – like name, email, address or even an IP address, whereas processing of personal data refers to “any operation or set of operations which is performed on personal data”. Therefore, a simple operation of storing an IP address on your web server logs constitutes processing of personal data of a user. Should GDPR be taken seriously? Organisation of websites has time until May 2018 to comply with the regulations set by the GDPR. The penalty for non-compliance can be 4% of annual global turnover, up to a maximum of €20 million.\nThere are various slabs of penalties according to the seriousness of the breach, which has been described in the FAQ section of the GDPR portal.\nSuch a high amount of penalties has been proposed to increase compliance. However, one may wonder what steps for the supervision of websites are in place. Supervisory Authorities (SA) of different member states are going to be set up, with the full support of the law. Each member state may have multiple SAs, depending on the constitutional, administrative and organisational structures. There are various powers that SAs will have:\ncarry out audits on websites, issue warnings for non-compliance, issue corrective measures to be followed with deadlines. SAs have both investigative and corrective powers to check compliance with the law and suggest changes to be compliant.\nIt is too early to speculate how SAs of various member states would interlink and work together, but one aspect is evident; SAs would enjoy the considerable power to enforce the GDPR guidelines.\nSix months after the guidelines were released, PwC surveyed 200 CXOs of large US firms to assess the impact of the GDPR guidelines. The results revealed that a majority of the businesses had taken up the GDPR guidelines as their top data protection priority, with 76% of them prepared to spend more than $1 million on GDPR. This shows that owing to a substantial presence in the EU, and large corporations are taking up the GDPR compliance seriously.\nThe details of your Website GDPR compliance So with all the official information out of the way, let’s take a moment to talk about how to make sure that your website is compliant and that you won’t experience any Website GDPR problems.\nBefore you move on to each of the aspects and how to comply with them, a security audit on your website site should, in general, reveal how data is being processed and stored on your servers, and steps that are required to comply with the GDPR.\nSome usual ways in which a standard website site might collect user data:\nuser registrations, comments, contact form entries, analytics and traffic log solutions, any other logging tools and plugins, security tools and plugins. Here are some key aspects of the website GDPR that users need to take care of:\n(a) Breach notification Under the GDPR compliance, if your website is experiencing a data breach of any kind, that violation needs to be communicated to your users.\nA data breach may result in a risk for the rights and freedoms of individuals, due to which notifying users promptly becomes necessary. Under the GDPR, a notification must be sent within 72 hours of first becoming aware of a breach. Data processors are also required to notify users as well as the data controllers, immediately after early becoming aware of a data breach.\nIn a website scenario, if you notice a data breach, you would need to notify all those affected by the breach within this designated time frame. However, the complexity here is the definition of the term “user” – it may constitute regular website users, contact form entries, and potentially even commenters.\nThis clause of the GDPR thus creates a legal requirement to assess and monitor the security of your website. The ideal way is to watch web traffic and web server logs.\n(b) Data collection, processing and storage Three elements of this: Right to Access, Right to Be Forgotten and Data Portability.\nThe right to access provides users with complete transparency in data processing and storage – what data points are being collected, where are these data points being processed and stored, and the reason behind the collection, processing and storage of the data. Users will also have to be provided with a copy of their data free of cost within 40 days. The right to be forgotten gives users an option to erase personal data, and stop further collection and processing of the data. This process involves the user withdrawing consent for their own data to be used. The data portability clause of the GDPR provides users with a right to download their data, for which they have previously given consent, and further transmit that data to a different controller. Privacy by design encourages controllers to enforce data policies which enable the processing and storage of only that data which is necessary. This helps site owners and controllers to adopt potentially safer procedures for data, by limiting the access to some data points.\nAs a website site owner, you first need to publish a detailed policy on which personal data points you’re using, how they are being processed and stored.\nNext, you need to have a setup to provide users with a copy of their data. This is perhaps the most challenging part of the process. However, we can assume that when the time comes, most plugin developers or tool developers – for the tools and plugins that you have on your site – will have already come forward with their solutions to this.\nIt is still advised, however, to have a system in place to derive the required data out of your database.\nFurther, it may be wise to avoid data storage altogether in some instances. For instance, contact forms could be set up to directly forward all communication to your email address instead of storing them anywhere on the web server.\n(c) Use of plugins or tools – implications of GDPR compliance Any plugin or tool that you use will also need to comply with the GDPR rules. As a site owner, it is still your responsibility, though, to make sure that every plugin can export/provide/erase user data it collects in compliance with the GDPR rules.\nThis can still mean some tough times for some of the most popular plugins out there. For instance, solutions like Gravity Forms have a lot of modules that collect user data by nature. How are those tools going to comply with the GDPR accurately?\nFor plugins too, the same rules apply, although they must be approached from the website owner. Each plugin needs to establish a data flow and inform about the processing of personal data. If you are the developer of a plugin, consider providing users of your plugin an addendum that they may add to their website’s terms to make them GDPR compliant. Gravity Forms, for instance, needs to let the user know how personal data being filled in a contact form is going to be published, and an option to get it removed, if necessary.\nAlso, some tools that sit seemingly outside of your website will see the impact of this too. Take, email marketing tools, for example. It’s a common practice to have those integrated with your site and to send promotional emails based on a list of email addresses. Depending on how you run your newsletters/lists, those addresses might not have been obtained by getting explicit consent from users.\nFor instance, a checkbox that’s selected by default would count as a violation. Under the GDPR, everything that’s part of your online presence as a business will need to collect consent and have a privacy policy in place explicitly. There are other implications too – if you wish to buy a mailing list, you would be sending emails illegally to the recipients, since no one explicitly asked to receive emails from you.\nAlthough the final responsibility lies with the site owner, webmasters themselves may have to look into its processes to become compliant as well.\nFinal thoughts To sum up what it means to make your website GDPR compliant:\nthe law comes into effect in May 2018, it applies to any site that deals with personal information of EU users, it gives the user the right to control the flow of their personal information, there are defined processes to monitor compliance, and huge fines are in place for non-compliance. In a nutshell, to make your website GDPR compliant, you should\nlook into all the different ways in which you’re collecting visitor data. Next, put mechanisms in place to make sure that users can control their data. Additionally, it’s probably a good idea to avoid collecting user data where it’s not necessary (like the contact form example from above). And most importantly of all, even if you’re using third-party tools and solutions, you still need to make sure that those are GDPR compliant as well. If you don’t have all of the above-taken care of by May 2018, trouble.\nNonetheless, the GDPR regulation is the right step in ensuring transparency in the handling of data. Although this post has covered the basics of GDPR, you may want to go through the regulation in detail if you have a profitable business running on your website. Remember, not complying can be fined up to €20 million or 4% of your global revenue.\nSome further reading:\nUK Information Commission’s Office paper White papers: by Actiance.com, by iapp.org Wikipedia page on the GDPR Original article by Shaumik Daityari ","date":"22 November 2017","externalUrl":null,"permalink":"/gdpr-and-your-website/","section":"Articles","summary":"On 25th May 2018, the GDPR (General Data Protection Regulation) enacted by the EU will come into effect.\nHow do you make your website GDPR compliant? What are the steps that you must take to ensure that you follow the guidelines? What if you neglect this? This article will help you in your endeavour to be ready when the regulation kicks in.\n","title":"GDPR and your website","type":"articles"},{"content":"Entity Framework is always a pain the back side when it comes to managing multiple database and know what to do if things get out of sync, an article by Anders Abel clearly lays out what need to be done and what can be used to sort out any sync problems, here is a snip from his article:\nEntity Framework Migrations are handled from the package manager console in Visual Studio. The usage is shown in various tutorials, but I haven’t found a complete list of the commands available and their usage, so I created my own. There are four available main commands.\nEnable-Migrations: Enables Code First Migrations in a project. Add-Migration: Scaffolds a migration script for any pending model changes. Update-Database: Applies any pending migrations to the database. Get-Migrations: Displays the migrations that have been applied to the target database. There are also three extra commands that are used by NuGet packages that install Entity Framework providers. These commands are not usually used as part of normal application development.\nAdd-EFProvider: Adds or updates an Entity Framework provider entry in the project config file. Add-EFDefaultConnectionFactory: Adds or updates an Entity Framework default connection factory in the project config file. Initialize-EFConfiguration: Initializes the Entity Framework section in the project config file and sets defaults. Original post from Anders Abel,\n","date":"13 November 2017","externalUrl":null,"permalink":"/ef-migrations-command-reference/","section":"Articles","summary":"Entity Framework is always a pain the back side when it comes to managing multiple database and know what to do if things get out of sync, an article by Anders Abel clearly lays out what need to be done and what can be used to sort out any sync problems, here is a snip from his article:\n","title":"EF Migrations Command Reference","type":"articles"},{"content":"Data privacy and data security have become one of the most prominent topics in organizations in almost every industry across the globe. New regulations are emerging that formalize requirements around these topics, and compel organizations to comply.\nThe upcoming EU Global Data Protection Regulation (GDPR) is one of the most noteworthy of these new regulations.\nThe GDPR takes effect on 25th May 2018 and sets a new global bar for privacy rights, security, and compliance. It mandates many requirements and obligations on organizations across the globe. Complying with this regulation will necessitate significant investments in data handling and data protection for a very large number of organizations.\nMicrosoft has produced some guidelines for SQL Service, which can be found here: microsoft-sql-and-the-gdpr\nFor more information on the GDPR, please visit the EU GDPR page.\nFor an in-depth guide on how Microsoft can help customers being their journey to GDPR compliance, see Beginning your General Data Protection Regulation (GDPR) Journey.\nTo learn more about Microsoft’s commitment to privacy and GDPR principles, visit the Trust Center GDPR site atwww.microsoft.com/GDPR.\n","date":"10 November 2017","externalUrl":null,"permalink":"/gdpr-and-sql-server/","section":"Articles","summary":"Data privacy and data security have become one of the most prominent topics in organizations in almost every industry across the globe. New regulations are emerging that formalize requirements around these topics, and compel organizations to comply.\n","title":"GDPR and SQL Server","type":"articles"},{"content":"Let’s start with a simple JSON string. In most cases, you will get this string from a web service call. For the sake of this tutorial, we will do this manually.\nvar example1 = @\"{\"\"name\"\":\"\"John Doe\"\",\"\"age\"\":20}\"; example1 is a simple JSON object with 2 fields: name and age.\nIn order to access the field(s) in this JSON string, we need to deserialize it into something C# can understand. This is where I would like to introduce the JavaScriptSerializer class, which is part of the System.Web.Script namespace.\nvar JSONObj = new JavaScriptSerializer().Deserialize\u0026lt;Dictionary\u0026lt;string, string\u0026gt;\u0026gt;(example1); What this line does is it deserializes the string example1 into an object of type Dictionary\u0026lt;string, string\u0026gt;.\nOnce we have done that, we can access the fields like this:\nJSONObj[\"name\"]; // equals John Doe JSONObj[\"age\"]; // equals 20 Note: the Dictionary definition must match the types of the values in our JSON. “John Doe” is a string but 20 is an integer, so we have to use \u0026lt;string, string\u0026gt; and not \u0026lt;string, int\u0026gt;.\nOkay, so we have deserialized it but you still have to reference it in a clunky way – object[\"field_name\"] – so let’s fix that!\nFirst, create a class which matches the definition of your JSON. In our case, we need a class with a string property and an int property:\nclass Example1Model { public string name { get; set; } public int age { get; set; } } And now, to deserialize our JSON into an object of that type:\nvar example1Model = new JavaScriptSerializer().Deserialize\u0026lt;Example1Model\u0026gt;(example1); And to reference the fields:\nexample1Model.name; // equals John Doe example1Model.age; // equals 20 As you can see, this is much cleaner! Your IDE will give you intellisense/auto-completion, type information and everything you would expect from a native type in .NET.\nShow me more! Our first example was great, but it was basic. Now let us handle a complex JSON string — how about a list of orders for a customer?\nvar example2 = @\"{\"\"custId\"\": 123, \"\"ordId\"\": 4567, \"\"items\"\":[{\"\"prodId\"\":1, \"\"price\"\":9.99, \"\"title\"\":\"\"Product 1\"\"},{\"\"prodId\"\":78, \"\"price\"\":95.99, \"\"title\"\":\"\"Product 2\"\"},{\"\"prodId\"\":1985, \"\"price\"\":3.01, \"\"title\"\":\"\"Product 3\"\"}] }\"; As in example 1, the first thing we need to do is to create your classes, which represent the data in JSON. Here, I created 2 classes — the CustomerOrderSummary is for the outer fields (custId and ordId) and a list of objects of type Item.\nclass Item { public int prodId { get; set; } public double price { get; set; } public string title { get; set; } } class CustomerOrderSummary { public int custId { get; set; } public int ordId { get; set; } public List\u0026lt;Item\u0026gt; items { get; set; } } And to deserialize the JSON we simply do:\nvar example2Model = new JavaScriptSerializer().Deserialize\u0026lt;CustomerOrderSummary\u0026gt;(example2); And to reference the fields:\nexample2Model.custId; // equals 123 example2Model.ordId; // equals 4567 example2Model.items.Count; // equals 3 example2Model.items[0].price // equals 9.99 There you have it! You can now parse JSON into .NET objects using C#! If you would like to retrieve and read the JSON via Objective-C and Node.js, feel free to read these two articles: iOS QuickTip: Getting and Reading JSON Data from a URL and How to Use JSON files in Node.js\nOther Useful references:\nwww.json.org www.json2code.com original article\n","date":"9 November 2017","externalUrl":null,"permalink":"/parse-json-into-a-c-object/","section":"Articles","summary":"Let’s start with a simple JSON string. In most cases, you will get this string from a web service call. For the sake of this tutorial, we will do this manually.\nvar example1 = @\"{\"\"name\"\":\"\"John Doe\"\",\"\"age\"\":20}\"; example1 is a simple JSON object with 2 fields: name and age.\n","title":"Parse JSON into a C# Object","type":"articles"},{"content":"I was asked a question today about what was the difference between POST and PUT when referring to HTTP.\nThere seems to be some confusion over what people understand it to be; it is quite simple, just to avoid any confusion here is the RFC itself explains the core difference:\nThe fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request — the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI, it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.\n","date":"31 August 2017","externalUrl":null,"permalink":"/difference-between-post-and-put/","section":"Articles","summary":"I was asked a question today about what was the difference between POST and PUT when referring to HTTP.\nThere seems to be some confusion over what people understand it to be; it is quite simple, just to avoid any confusion here is the RFC itself explains the core difference:\n","title":"Difference between POST and PUT","type":"articles"},{"content":"Source control packages always have been a bit of a pain when you first start using them. You may know the principles of source control. Each environment has its own way and definitions and its own processes. Once you are used to using a source control system and the steps you follow it is easy. I call this the Source Control shuffle.\nIt’s always good to have a workflow that allows for code review and this process below will provide a method to do this by using branches and merging back into the master.\nThe branching, committing and merging workflow for projects using git source control. Guiding Principals master is always production ready and suitable for deployment create a new branch for every feature or fix on each branch, NEVER work on anything but the specific task related to it. If you see other work that needs doing during the course of development, submit a ticket for it, or check out a new branch. rebase during feature development, explicit ( --no-ff ) merge when complete. Feature Process (or the shuffle) New features that are added to the product for a future release.\nN.B. bug fixes that should go into the next feature release, rather than a hotfix, should also use this process.\nPull down the latest changes from master.\ngit checkout master git fetch origin git merge master Create a new branch for the work. Use the issue key followed by a descriptive name for the branch. git checkout -b PRJ-123-feature-name Work on the feature. Make regular commits Avoid clustering changes together. Push to remote as needed, to keep a backup of your work. If you need to work on another task, ensure all changes are committed before creating a new branch or switch to another one. Only one developer should work on a feature branch. If more than one developer needs to work on the task, each should branch off again (including the first developer to start work) from the shared branch. Merges should be made to the task branch as per the central workflow. Keep your branch up to date with the latest changes on master\ngit fetch origin git rebase origin/master When ready for feedback and/or code review, push to remote and create a pull request.\nPush to remote:\ngit push -u origin PRJ-123-feature-name\nCreate a pull request on VSTS to merge the feature branch into master:\\ Code review should now occur. If changes are required, they can be committed and pushed to the same branch. The pull request will be automatically updated with any new commits.\nN.B. Any changes made from now on should occur using merges only. If master needs to be merged into the branch to update it, you should not use rebase, as this will cause problems with the pull request.\nOnce the review is complete, perform a final rebase (see Feature Process above) to prepare to merge. Then push to remote again (see 5.a above). The pull request should now be completed on VSTS. This will create a merge commit. There should be no actual changes or conflicts in this commit if the previous procedures have been followed correctly. Delete the feature branch. This is an option on the remote during the pull request completion in VSTS. The branch will also need to be deleted locally by the developer: git branch -d PRJ-123-feature-name Hotfix Process Bug fixes that need to be applied to the currently released version (or to patch a previous version that is still supported) and require a new patch version release.\nPull down the latest changes from master (see Feature Process 1. above). Check out the tag of the release you want to hotfix, branch from it and check out the new branch:\ngit checkout v1.0.0 git branch PRJ-199-hotfix-name git checkout PRJ-199-hotfix-name Work on the bug fix, following the notes in Feature Process 3.\nN.B. It is important that you DO NOT follow step 4. of Feature Process, as changes from master should not be brought into your hotfix branch. When ready for feedback and/or code review, push to remote.\nN.B. DO NOT create a pull request to master. Follow the Release Process, using the hotfix branch instead of a release branch.\nN.B. hotfix/patch releases should contain just one bug fix. Release Process This process starts when preparing to make a release after all code tasks for that release are merged into master. Final work may still be necessary to complete the release.\nCreate a new branch from, master either in git directly, or locally, having first pulled the latest changes from master. If you create the branch locally, the currently checked out branch will be used to branch from. The branch should be named release with the version number appended, e.g. release-1.1.0\nThis marks the point at which no more features will be added to the release. Only adjustments and bug fixes necessary to put the release into production should be applied to this branch.\nHowever, work can continue on new features for other releases, by branching off, master as covered above. Any further work to prepare this release should be merged into this release branch, using the same process as Feature Process, but creating pull requests to and rebasing from the release branch, instead of master. Once the release is ready, update the assembly version in the release branch to match Jira and commit, then deploy the build via the deployment machine – this will usually involve checking out the new release branch, running the grunt script to grab the correct web configs and log4net configs and then deploying from Visual Studio.\nNote that the version number as reported in the health check will always have 4 digits even though we are only using 3. Create a tag on the release branch once you are happy that the release was successful\ngit checkout release-1.1.0 git tag v1.1.0 git push --tags origin release-1.1.0 Merge the release into master after the release has been tested and is finished: If there are any errors with the release, a decision will need to be made by the Development Manager whether to fix the release branch or to revert the release and do it again. Merging back into master should be done with a pull request on git. The release branch can now be deleted. ","date":"20 August 2017","externalUrl":null,"permalink":"/git-workflow/","section":"Articles","summary":"Source control packages always have been a bit of a pain when you first start using them. You may know the principles of source control. Each environment has its own way and definitions and its own processes. Once you are used to using a source control system and the steps you follow it is easy. I call this the Source Control shuffle.\n","title":"Git Workflow","type":"articles"},{"content":"","date":"24 July 2017","externalUrl":null,"permalink":"/categories/symmetric/","section":"Categories","summary":"","title":"Symmetric","type":"categories"},{"content":"The following is a symmetric encryption/decryption routine using AES in GCM mode. This code operates in the application layer and is meant to receive user-specific and confidential information and encrypt it, after which it is stored in a separate database server. It also is called upon to decrypt encrypted information from the database.\nThe full description of the AES in GCM mode can be found in this document produced by David A. McGrew and John Viega The Galois/Counter Mode of Operation (GCM)\n","date":"24 July 2017","externalUrl":null,"permalink":"/symmetric-encryptiondecryption-routine-using-aes/","section":"Articles","summary":"The following is a symmetric encryption/decryption routine using AES in GCM mode. This code operates in the application layer and is meant to receive user-specific and confidential information and encrypt it, after which it is stored in a separate database server. It also is called upon to decrypt encrypted information from the database.\n","title":"Symmetric encryption/decryption routine using AES","type":"articles"},{"content":"The DatabaseLayer is an abstraction for database access which means the calling application or library does not need to be tight-coupled to the database itself. A set of factory methods is available to call in order to create commands and parameters, all based on the .NET abstract base classes.\nCurrently supported engines are SQL server and MySQL, represented by “sql” and “mysql” in your web.config or app.config.\nThe DatabaseLayer does not use a provider pattern but the argument is passed in the factory to tell the library what database engine to use. An example is shown below. It is preferable to create one constant for the database type and share it across multiple places it is used.\nThe example below is lazy loaded and uses AppSettings and ConnectionStrings from the web.config or app.config file.\nprivate static Database database; internal static Database GetDb() { if ( database == null ) { database = Database.GetDatabase( ConfigurationManager.AppSettings[\u0026ldquo;databasetype\u0026rdquo;], ConfigurationManager.ConnectionStrings[\u0026ldquo;myconnection\u0026rdquo;].ConnectionString); } return database; }\nDatabaseLayer solution\n","date":"24 July 2017","externalUrl":null,"permalink":"/database-layer/","section":"Articles","summary":"The DatabaseLayer is an abstraction for database access which means the calling application or library does not need to be tight-coupled to the database itself. A set of factory methods is available to call in order to create commands and parameters, all based on the .NET abstract base classes.\n","title":"Database Layer","type":"articles"},{"content":"This is how, within your organisation, you can protect the data, especially in a cloud-first, multi-tenant world. The source will provide you with the concepts around encrypting enterprise data, look at what you should encrypt, and cover robust patterns and practices you can follow in your organisation.\nEnjoy.\nData encryption with azure\n","date":"23 June 2017","externalUrl":null,"permalink":"/azure-key-vault/","section":"Articles","summary":"This is how, within your organisation, you can protect the data, especially in a cloud-first, multi-tenant world. The source will provide you with the concepts around encrypting enterprise data, look at what you should encrypt, and cover robust patterns and practices you can follow in your organisation.\n","title":"Azure Key Vault","type":"articles"},{"content":"","date":"23 June 2017","externalUrl":null,"permalink":"/categories/key-vault/","section":"Categories","summary":"","title":"Key Vault","type":"categories"},{"content":"To get a level of how many data breaches are happening Breach Level Index provides this information, along with many other statistics\nhttp://breachlevelindex.com/\nNeed to check if you have an email account that has been compromised in a data breach when check out Have I Been Pwned to check if you have been compromised and also Signup to get email notifications\nhttps://haveibeenpwned.com/\nFor a collection of Cryptography APIs in one library\nhttps://www.bouncycastle.org\nHSM hardware\nhttps://www.thales-esecurity.com/products-and-services/products-and-services/hardware-security-moduleshttps://www.thales-esecurity.com/products-and-services/products-and-services/hardware-security-modules\n","date":"23 June 2017","externalUrl":null,"permalink":"/security-links-and-references/","section":"Articles","summary":"To get a level of how many data breaches are happening Breach Level Index provides this information, along with many other statistics\nhttp://breachlevelindex.com/\nNeed to check if you have an email account that has been compromised in a data breach when check out Have I Been Pwned to check if you have been compromised and also Signup to get email notifications\n","title":"Security Links and References","type":"articles"},{"content":"","date":"23 June 2017","externalUrl":null,"permalink":"/categories/app-service/","section":"Categories","summary":"","title":"App Service","type":"categories"},{"content":"Over the past week, I spent some time automating Azure App Service infrastructure with Azure Resource Manager (ARM) templates. I discovered a few tips and tricks along the way that I’ll describe in detail below…\nTake an environment name as a parameter Create sticky slot settings Variables aren’t just for strings Change the time zone of your web app Big thanks to David Ebbo’s talk at BUILD and his sample “WebAppManyFeatures” template; they are super handy resources for anyone who is working on writing their own ARM templates.\nEnvironment Name Parameter ARM templates are useful for creating the entire infrastructure for an application. Often this means creating infrastructure for each deployment environment (Dev, QA, Production, etc). Instead of passing in names for the service plans and web apps, I find it useful to pass in a name for the environment and use it as a suffix for all the names. This way we can easily use the same template to set up any environment.\n{ // ... \"parameters\": { \"environmentName\": { \"type\": \"string\" } }, \"variables\": { \"appServicePlanName\": \"[concat('awesomeserviceplan-', parameters('environmentName'))]\", \"siteName\": \"[concat('awesomesite-', parameters('environmentname'))]\" } // ... } In the above example, if we pass in “dev” as the,environmentName we get “awesomeserviceplan-dev” and “awesomesite-dev” as our resource names.\nSticky Slot Settings App settings and connection strings for a Web App slot can be marked as a “slot setting” (i.e., the setting is sticky to the slot). It’s not well documented how to specify sticky slot settings in an ARM template. It turns out we can do this using a config resource section called “slotconfignames” on the production site. Simply list the app setting and connection string keys that need to stick to the slot:\n{ \"apiVersion\": \"2015-08-01\", \"name\": \"slotconfignames\", \"type\": \"config\", \"dependsOn\": [ \"[resourceId('Microsoft.Web/Sites', variables('siteName'))]\" ], \"properties\": { \"connectionStringNames\": [ \"ConnString1\" ], \"appSettingNames\": [ \"AppSettingKey1\", \"AppSettingKey2\" ] } } Here’s how it’ll look like in the portal:\nObject Variables Variables are not only useful for declaring text that is used in multiple places; they can be objects too! This is especially handy for settings that apply to multiple Web Apps in the template.\n{ // ... \"variables\": { \"siteProperties\": { \"phpVersion\": \"5.5\", \"netFrameworkVersion\": \"v4.0\", \"use32BitWorkerProcess\": false, /* 64-bit platform */ \"webSocketsEnabled\": true, \"alwaysOn\": true, \"requestTracingEnabled\": true, /* Failed request tracing, aka 'freb' */ \"httpLoggingEnabled\": true, /* IIS logs (aka Web server logging) */ \"logsDirectorySizeLimit\": 40, /* 40 MB limit for IIS logs */ \"detailedErrorLoggingEnabled\": true, /* Detailed error messages */ \"remoteDebuggingEnabled\": true, \"remoteDebuggingVersion\": \"VS2013\", \"defaultDocuments\": [ \"index.html\", \"hostingstart.html\" ] } }, // ... } And now we can use the siteProperties variable for the production site as well as its staging slot:\n{ \"apiVersion\": \"2015-08-01\", \"name\": \"[variables('siteName')]\", \"type\": \"Microsoft.Web/sites\", \"location\": \"[parameters('siteLocation')]\", \"dependsOn\": [ \"[resourceId('Microsoft.Web/serverfarms', variables('appServicePlanName'))]\" ], \"properties\": { \"serverFarmId\": \"[variables('appServicePlanName')]\" }, \"resources\": [ { \"apiVersion\": \"2015-08-01\", \"name\": \"web\", \"type\": \"config\", \"dependsOn\": [ \"[resourceId('Microsoft.Web/Sites', variables('siteName'))]\" ], \"properties\": \"[variables('siteProperties')]\" }, { \"apiVersion\": \"2015-08-01\", \"name\": \"Staging\", \"type\": \"slots\", \"location\": \"[parameters('siteLocation')]\", \"dependsOn\": [ \"[resourceId('Microsoft.Web/Sites', variables('siteName'))]\" ], \"resources\": [ { \"apiVersion\": \"2015-08-01\", \"name\": \"web\", \"type\": \"config\", \"dependsOn\": [ \"[resourceId('Microsoft.Web/Sites/Slots', variables('siteName'), 'Staging')]\" ], \"properties\": \"[variables('siteProperties')]\" } ] } ] } Custom Time Zone There’s a little-known setting in Azure App Service that allows you to set the time zone on a per-app basis. It is done by creating an app setting called WEBSITE_TIME_ZONE in the portal. It means we can also do this in an ARM template:\n{ \"apiVersion\": \"2015-08-01\", \"name\": \"appsettings\", \"type\": \"config\", \"dependsOn\": [ \"[resourceId('Microsoft.Web/Sites', variables('siteName'))]\" ], \"properties\": { \"WEBSITE_TIME_ZONE\": \"Pacific Standard Time\" } } For more information on the time zone setting, check out this article.\nSource code: WebAppManyFeatures.json\n","date":"23 June 2017","externalUrl":null,"permalink":"/azure-resource-manager-templates-tips-and-tricks-for-a-application-service/","section":"Articles","summary":"Over the past week, I spent some time automating Azure App Service infrastructure with Azure Resource Manager (ARM) templates. I discovered a few tips and tricks along the way that I’ll describe in detail below…\n","title":"Azure Resource Manager Templates Tips and Tricks for a Application Service","type":"articles"},{"content":"I did some quick research on the SQL Server Firewall “Allow Access to Azure Services” option in Azure today.\nAnd I sorry to say that my fears were right, that by setting this option does pose a significant security risk and leaves the SQL Server vulnerable.\nHere is the extract of the article I found from Gaurav Hind at Microsoft\nAccess within Azure: This can be toggled by “Allow access to Azure services” Yes/No button on the portal (Firewall settings page). Please note, enabling this feature would allow any traffic from resources/services hosted in Azure (not just your Azure subscription) to access the database.\nhttps://blogs.msdn.microsoft.com/azureedu/2016/04/11/what-should-i-know-when-setting-up-my-azure-sql-database-paas/\nThe big question now is how do you plug this gap in the firewall? One possible solution is to build a virtual network within Azure or Filter network traffic with network security groups, this is beyond the scope of this article.\n","date":"14 June 2017","externalUrl":null,"permalink":"/allow-access-to-azure-services-what-does-this-actually-mean/","section":"Articles","summary":"I did some quick research on the SQL Server Firewall “Allow Access to Azure Services” option in Azure today.\nAnd I sorry to say that my fears were right, that by setting this option does pose a significant security risk and leaves the SQL Server vulnerable.\n","title":"Allow access to Azure services, what does this actually mean?","type":"articles"},{"content":"After writing about SecureStrings, you soon come to realise that holding the secret information you are going to have to make some comparisons at some point. For example, if you need to check a password.\nThe important thing to remember is not to expose the password as text or hold it in memory for anyone or anything to sniff it out.\nThis code snippet does the job, but it what it does expose is a Timing Attack, but we will deal with that issue another day.\npublic static bool IsEqualTo(this SecureString ss1, SecureString ss2) { if (ss1 == null) throw new ArgumentNullException(\"s1\"); if (ss2 == null) throw new ArgumentNullException(\u0026ldquo;s2\u0026rdquo;);\nif (ss1.Length != ss2.Length) return false;\nIntPtr bstr1 = IntPtr.Zero; IntPtr bstr2 = IntPtr.Zero; try { bstr1 = Marshal.SecureStringToBSTR(ss1); bstr2 = Marshal.SecureStringToBSTR(ss2);\nint length1 = Marshal.ReadInt32(bstr1, -4);\nfor (int x = 0; x \u0026lt; length1; ++x) { byte b1 = Marshal.ReadByte(bstr1, x); byte b2 = Marshal.ReadByte(bstr2, x); if (b1 != b2) return false; } return true; } finally { if (bstr2 != IntPtr.Zero) Marshal.ZeroFreeBSTR(bstr2); if (bstr1 != IntPtr.Zero) Marshal.ZeroFreeBSTR(bstr1); } }\nSecureString\n","date":"8 June 2017","externalUrl":null,"permalink":"/comparing-securestrings/","section":"Articles","summary":"After writing about SecureStrings, you soon come to realise that holding the secret information you are going to have to make some comparisons at some point. For example, if you need to check a password.\n","title":"Comparing SecureStrings","type":"articles"},{"content":"","date":"8 June 2017","externalUrl":null,"permalink":"/categories/uncategorized/","section":"Categories","summary":"","title":"Uncategorized","type":"categories"},{"content":"When comparing two MACs or hashes (also password hashes) for equality you would first think a simple comparison would be okay? Think again as they are susceptible to timing attacks.\nIn cryptography, a timing attack is a side channel attack in which the attacker attempts to compromise a cryptosystem by analysing the time taken to execute cryptographic algorithms.\nIf you want to read more about this take a look at this article.\nif ($hash1 == $hash2) { //mac verification is Okay return \"hashs are equal\" } else { //something happened return \"hashs verification failed!\"; } Okay, so what is wrong with this?\nBoth arguments must be of the same length to be compared successfully. When arguments of differing length are supplied, FALSE is returned immediately and the length of the known string may be leaked in the case of a timing attack. It is done by timing the amount of time it takes to compare a known string length with the HASH, and as you will then find the length of the string based on the time it takes during the comparison.\nCompares two-byte arrays in length-constant time. This comparison method is used so that password hashes cannot be extracted from on-line systems using a timing attack and then attacked off-line.\nprivate static bool SlowEquals(byte[] a, byte[] b) { uint diff = (uint)a.Length ^ (uint)b.Length; for (int i = 0; i \u0026lt; a.Length \u0026amp;\u0026amp; i \u0026lt; b.Length; i++) diff |= (uint)(a[i] ^ b[i]); return diff == 0; } What does the line diff |= (uint)(a[i] ^ b[i]); do?\nThis sets diff based on whether there’s a difference between a and b.\nIt avoids a timing attack by always walking through the entirety of the shorter of the two of a and b, regardless of whether there’s a mismatch sooner than that or not.\nThe diff |= (uint)(a[i] ^ (uint)b[i]) takes the exclusive-or of a byte of a with a corresponding byte of b. That will be 0 if the two bytes are the same, or non-zero if they’re different. It then ors that with diff.\nTherefore, diff will be set to non-zero in an iteration if a difference was found between the inputs in that iteration. Once diff is given a non-zero value at any iteration of the loop, it will retain the non-zero value through further iterations.\nTherefore, the final result in diff will be non-zero if any difference is found between corresponding bytes of a and b, and 0 only if all bytes (and the lengths) of a and b are equal.\nUnlike a typical comparison, however, this will always execute the loop until all the bytes in the shorter of the two inputs have been compared to bytes in the other. A typical comparison would have an early-out where the loop would be broken as soon as a mismatch was found:\nMicrosoft provides a SecureString to hold sensitive data, and this uses a generic method Equals(Object), which determines whether the specified object is equal to the current object. There is no information saying that Equals method protects against Timing Attacks. Therefore we can only conclude that it is not safe for this operation.\nI would suggest research into writing our own String Compare that is protected against Timing Attacks.\nI’m not sure about all of this and further research is required, I did find this article which would be worth considering:\nhttps://paragonie.com/blog/2015/11/preventing-timing-attacks-on-string-comparison-with-double-hmac-strategy\n","date":"6 June 2017","externalUrl":null,"permalink":"/cryptography-net-avoiding-timing-attack/","section":"Articles","summary":"When comparing two MACs or hashes (also password hashes) for equality you would first think a simple comparison would be okay? Think again as they are susceptible to timing attacks.\nIn cryptography, a timing attack is a side channel attack in which the attacker attempts to compromise a cryptosystem by analysing the time taken to execute cryptographic algorithms.\n","title":"Cryptography .NET, Avoiding Timing Attack","type":"articles"},{"content":"Setting up Azure Key Vault for use within a .NET application is not an easy process, as it is a secure environment and security is required to gain access, which involved the Active Directly Application registrations and Access Policies.\nI’ve created a quick setup guide based on the Azure Portal that is available at the time of setting up this article.\n","date":"6 June 2017","externalUrl":null,"permalink":"/azure-key-vault-setting-up/","section":"Articles","summary":"Setting up Azure Key Vault for use within a .NET application is not an easy process, as it is a secure environment and security is required to gain access, which involved the Active Directly Application registrations and Access Policies.\n","title":"Azure Key Vault Setting up","type":"articles"},{"content":"I’ve come across a class in the System.Security namespace that is often overlooked. The class is SecureString. In this post, I will go over what SecureString is and why it is needed.\nHave you ever come across these scenarios before?\nA password appears in a log file accidentally. A password is being shown at somewhere – once a GUI did show a command line of application that was being run, and the command line consisted of the password. Using memory profiler to profile software with your colleague. Colleague sees your password in memory. Using RedGate software that could capture the “value” of local variables in case of exceptions, amazingly useful. Though, I can imagine that it will log “string passwords” accidentally. A crash dump that includes string password. Do you know how to avoid all these problems? SecureString. It makes sure you don’t make silly mistakes as such. How does it avoid it? By making sure that password is encrypted in unmanaged memory and the real value can be only accessed when you are 90% sure what you’re doing.\nIn the sense, SecureString works pretty easily:\nEverything is encrypted User calls AppendChar Decrypt everything in UNMANAGED MEMORY and add the character Encrypt everything again in UNMANAGED MEMORY. What if the user has access to your computer? Would a virus be able to get access to all the SecureStrings? Yes. All you need to do is hook yourself into RtlEncryptMemory then decrypt the memory, and you will get the location of the unencrypted memory address, and read it out. Voila! In fact, you could make a virus that will continuously scan for usage of SecureString and log all the activities with it. I am not saying it will be an easy task, but it can be done. As you can see, the “powerfulness” of SecureString is completely gone once there’s a user/virus on your system.\nYou have few points in your post. Sure, if you use some of the UI controls that hold “string password” internally, using actual SecureString is not that useful.\nThe bottom line is; if you have sensitive data(passwords, credit cards, ..), use SecureString. This is what C# Framework is following. For example, NetworkCredential class stores password as SecureString. If you look this, you can see over ~80 different usages in .NET framework of SecureString.\nThere are many cases when you have to convert SecureString to string because some API expects it.\nThe usual problem is either:\nThe API is GENERIC. It does not know that there’s a sensitive data. The API knows that it’s dealing with sensitive data and uses “string” – that’s just bad design. You raised a good point: what happens when you convert SecureString to a string? That can only happen because of the first point. Eg the API does not know that it’s sensitive data. I have personally not seen that happening. Getting string out of SecureString is not that simple.\nIt’s not simple for a simple reason; it was never intended to let the user convert SecureString to string, as you stated: GC will kick in. If you see yourself doing that, you need to step back and ask yourself: Why am I even doing this, or do I need this, why?\nYou can always extend the SecureString class with an extension method, such as ToEncryptedString(__SERVER__PUBLIC_KEY), which gives you a string instance of SecureString that is encrypted using server’s public key. The only server can then decrypt it. Problem solved, GC will never see the “original” string, as you never expose it in managed memory. This is precisely what is being done in PSRemotingCryptoHelper (EncryptSecureStringCore(SecureString secureString)).\nAnd as something very almost-related: Mono SecureString does not encrypt at all. The implementation has been commented out because ..wait for it. “It somehow causes nunit test breakage”, which brings to my last point:\nNot supported everywhere is SecureString. If the platform/architecture does not support SecureString, you’ll get an exception. The recommended list of deployment platforms is documentation.\nUsing SecureString for Sensitive Data The standard System.String class has never been a very secure solution for storing sensitive strings such as passwords or credit card numbers. Using a string for this purposes has numerous problems including it’s not pinned, so the garbage collector can move it around and will leave several copies in memory, it’s not encrypted, so anyone who can read your processor’s memory will be able to see the values of the string easily. Also, if your process gets swapped out to disk, the unencrypted contents of the string will be sitting in your swap file. And it’s not mutable, so whenever you need to modify it there will be an old version and the new version both in memory.\nSince it’s not mutable, there’s no effective way to clear it out when you’re done using it. Secure strings are held in encrypted memory by the CLR using the Data Protection API, or DPAPI, and they’re only unencrypted when they are accessed. This limits the amount of time that your string is in plain text for an attacker to see.\nThe garbage collector will not move the encrypted string around in memory, so you never have to worry about multiple copies of your string sitting in your address space, unless you make copies of those.\nSecureString also implements IDisposable, and when it’s disposed of or finalised if you forget to dispose of it, the memory that was used to hold your encrypted string will be zeroed out.\nThey also provide a feature that lets you lock them down as read only preventing other code from modifying your string.\nYou can create a secure string with a pointer to a character array and a length of that array. When constructed this way, the secure string will make a copy of your array, allowing you to zero out your insecure copy.\nA secure string can also be constructed without an existing character array, and the data can be copied in one character at a time.\nOne important thing to note though is that SecureString shouldn’t be used as a blanket replacement for System.String, it should only be used in places where you need to store sensitive information that you do not want to spread around in memory for longer than is required.\nTo add data or modify data in your string, standard operations are provided. For instance, you’ll find an AppendChar, InsertAt, RemoveAt, and SetAt methods. MakeReadOnly and IsReadOnly allows you to lock down the secure string. Clear, Dispose, and the finaliser takes care of removing any trace of the safe string from memory.\nThe main idea with SecureString is that you would never store a password or other textual secret in plain text. Unfortunately, SecureString was introduced into the framework only after plenty of APIs were built and shipped using passwords stored in a string, such as the System.Net.NetworkCredential. So any application that must use these APIs had no option but to convert secure strings to strings.\nHowever, the SecureString class itself doesn’t provide any method to get back a plain string with its content, precisely to discourage this type of usage. What a developer has to do is use functions from the System.Runtime.InteropServices.Marshal to get a native buffer with the plain string, marshal a value into managed string, and then very importantly free the native buffer. The best implementation to get a string out of a secure string is to use a try/finally block to free the native buffer.\nHere is a sample application showing how you can use SecureString, please remember in production do not use the SecureString to String as this just does not make sense and would make it insecure.\nSecureString\nHere is a short method to convert a string to a SecureString\npublic static SecureString ToSecureString(this string source) { if (string.IsNullOrWhiteSpace(source)) return null; else { SecureString result = new SecureString(); foreach (char c in source.ToCharArray()) result.AppendChar(c); return result; } } ","date":"2 June 2017","externalUrl":null,"permalink":"/securestring/","section":"Articles","summary":"I’ve come across a class in the System.Security namespace that is often overlooked. The class is SecureString. In this post, I will go over what SecureString is and why it is needed.\nHave you ever come across these scenarios before?\n","title":"SecureString","type":"articles"},{"content":"There are occasions where you are aware of many exceptions within your code that you want to raise together in one go. Perhaps your system makes a service call to a middleware orchestration component that potentially returns many exceptions detailed in its response, or another scenario might be a batch processing task dealing with many items in one process that require you to collate all exceptions until the end and then throw them together.\nLet us look at the batch scenario in more detail. In this situation, if you raised the first exception that you found it would exit the method without processing the remaining items. Alternatively, you could store the exception information in a variable of some sort and once all the elements are processed using the information to construct an exception and throw it. While this approach works, there are some drawbacks. There is the extra effort required to create a viable storage container to hold the exception information, and this may mean modifying existing code not to throw an exception but instead to log the details in this new ‘exception detail helper class’. This solution also lacks the additional benefits you get with creating an exception then, for example, the numerous intrinsic properties that exist within Exception objects that provide valuable additional context information to support the message within the exception. Even when all the relevant information has been collated into a single exception class, then you are still left with one exception holding all that information when you may need to handle the exceptions individually and pass them off to existing error handling frameworks which rely on a type deriving from Exception.\nLuckily included in .Net Framework 4.0 is the simple but very useful AggregateException class which lives in the System namespace (within mscorlib.dll). It was created to use the Task Parallel Library, and its use within that library is described on MSDN here. Don’t think that is it’s only used though, as it can be put to good use within your code in situations like those described above where you need to throw many exceptions, so let’s see what it offers.\nThe AggregateException class is an exception type, inheriting from System.Exception, that acts a wrapper for a collection of child exceptions. Within your code, you can create instances of any exception based type and add them to the AggregateException’s collection. The idea is a simple one, but the AggregateException’s beauty comes in the implementation of this simplicity. As it is a regular exception class, it can handle in the usual way by existing code but also as a unique exception collection by the particular system that cares about all the exceptions nested within its bowels.\nThe class accepts the child exceptions on one of its seven constructors and then exposes them through its InnerExceptions property. Unfortunately, this is a read-only collection, and so it is not possible to add inner exceptions to the AggregateException after it has instantiated (which would have been nice) and so you will need to store your exceptions in a collection until you’re ready to create the Aggregate and throw it:\n// create a collection container to hold exceptions List\u0026lt;Exception\u0026gt; exceptions = new List\u0026lt;Exception\u0026gt;(); // do some stuff here ........ // we have an exception with an innerexception, so add it to the list exceptions.Add(new TimeoutException(\"It timed out\", new ArgumentException(\"ID missing\"))); // do more stuff ..... // Another exception, add to list exceptions.Add(new NotImplementedException(\"Somethings not implemented\")); // all done, now create the AggregateException and throw it AggregateException aggEx = new AggregateException(exceptions); throw aggEx; The method you use to store the exceptions is up to you as long as you have them all ready at the time you create the AggregateException class. Seven constructors are allowing you to pass combinations of nothing, a string message, collections or arrays of inner exceptions.\nOnce created you interact with the class as you would any other exception type:\ntry { // do task } catch (AggregateException ex) { // handle it } The key as it means that you can make use of existing code and patterns for handling exceptions within your (or third parties) codebase.\nIn addition to the general Exception members, the class exposes a few custom ones. The common InnerException property is there for compatibility, and this appears to return the first exception added to the AggregateException class via the constructor, so in the example above it would be the TimeoutException instance. All of the child exceptions expose via the InnerExceptions read-only collection property (as shown below).\nThe Flatten() method is another custom property that might prove useful if you find the need to nest Exceptions as inner exceptions within several AggregateExceptions. The method will iterate the InnerExceptions collection, and if it finds AggregateExceptions nested as InnerExceptions, it will promote their child exceptions to the parent level. As you can see in this example:\nAggregateException aggExInner = new AggregateException(\"inner AggEx\", new TimeoutException()); AggregateException aggExOuter1 = new AggregateException(\"outer 1 AggEx\", aggExInner); AggregateException aggExOuter2 = new AggregateException(\"outer 2 AggEx\", new ArgumentException()); AggregateException aggExMaster = new AggregateException(aggExOuter1, aggExOuter2); If we create this structure above of AggregrateExceptions with inner exceptions of TimeoutException and ArgumentException then the InnerExceptions property of the parent AggregateException (i.e. aggExMaster) shows, as expected, two objects, both being of type AggregrateException and both containing child exceptions of their own:\nBut if we call Flatten()…\nAggregateException aggExFlatterX = aggExMaster.Flatten(); …we get a new ArgumentException instance returned that contains still two objects, but this time the AggregrateException objects have gone, and we have the two child exceptions of TimeoutException and ArgumentException:\nA useful feature to discard the AggregateException containers (which are effectively just packaging) and expose the real meat, i.e. the real exceptions that have been thrown and needs to be addressed.\nIf you’re wondering how the ToString() is implemented then the aggExMaster object in the examples above (without flattening) produces this:\nSystem.AggregateException: One or more errors occurred. ---\u0026gt; System.AggregateException : outer 1 AggEx ---\u0026gt; System.AggregateException: inner AggEx ---\u0026gt; System.TimeoutException: The operation has timed out. --- End of inner exception stack trace --- --- End of inner exception stack trace --- --- End of inner exception stack trace ------\u0026gt; (Inner Exception #0) System.AggregateException: outer 1 AggEx ---\u0026gt; System.AggregateException: inner AggEx ---\u0026gt; System.TimeoutException: The operation has timed out. --- End of inner exception stack trace --- --- End of inner exception stack trace ------\u0026gt; (Inner Exception #0) System.AggregateException: inner AggEx ---\u0026gt; System.TimeoutException: The operation has timed out. --- End of inner exception stack trace ------\u0026gt; (Inner Exception #0) System.TimeoutException: The operation has timed out.\u0026lt;---\u0026lt;---\u0026lt;------\u0026gt; (Inner Exception #1) System.AggregateException : outer 2 AggEx --- System.ArgumentException: Value does not fall within the expected range. --- End of inner exception stack trace ------\u0026gt; (Inner Exception #0) System.ArgumentException: Value does not fall within the expected range. As you can see the data has been formatted in a neat and convenient way for readability, with separators between the inner exceptions.\nIn summary, this is a very useful class to be aware of and have in your arsenal whether you are dealing with the Parallel Tasks Library or you just need to manage multiple exceptions. I like simple and neat solutions, and to me, this is a good example of that philosophy.\nOrginal Article ","date":"24 May 2017","externalUrl":null,"permalink":"/raising-multiple-exceptions-with-aggregateexception/","section":"Articles","summary":"There are occasions where you are aware of many exceptions within your code that you want to raise together in one go. Perhaps your system makes a service call to a middleware orchestration component that potentially returns many exceptions detailed in its response, or another scenario might be a batch processing task dealing with many items in one process that require you to collate all exceptions until the end and then throw them together.\n","title":"Raising Multiple Exceptions with AggregateException","type":"articles"},{"content":"","date":"16 May 2017","externalUrl":null,"permalink":"/categories/nosql/","section":"Categories","summary":"","title":"NoSQL","type":"categories"},{"content":"If you want to setup MongoDB with C#, then the best option is to follow the getting started guide on the MongoDB website\nhttps://docs.mongodb.com/getting-started/csharp/client/\nYou can install the NuGet package for MongoDB by typing into the Package Manager Console\n“Install-Package MongoDB.Driver” Although MongoDB does provide an example that you can work through, I did find that the MoveNextAsync command is no longer supported and the case fails.\nI built a simple application that uses MongoDB CRUD application that works very well to show how it can be implemented.\nMongoDB\nHere is a helpful MongoDB tool to administer your Mongo database, Robomogo\nhttps://robomongo.org\nOn my searching to find good source of material I came across this nice video demo here https://youtu.be/ubwC63DwJ8w\n","date":"16 May 2017","externalUrl":null,"permalink":"/using-mongodb/","section":"Articles","summary":"If you want to setup MongoDB with C#, then the best option is to follow the getting started guide on the MongoDB website\nhttps://docs.mongodb.com/getting-started/csharp/client/\nYou can install the NuGet package for MongoDB by typing into the Package Manager Console\n","title":"Using MongoDB","type":"articles"},{"content":"This post is to show how to setup a customised configuration section in your app.config or web.conifg of your .NET application\nI have written an article on this before, back in 2008, but things have moved on in the libraries and this is the latest and easiest way to create your own customised configuration.\nWe just need to define our class, inherit from System.Configuration.ConfigurationSection, and add a property per setting we wish to store.\nusing System; using System.Configuration; public class BlogSettings : ConfigurationSection { private static BlogSettings settings = ConfigurationManager.GetSection(\u0026ldquo;BlogSettings\u0026rdquo;) as BlogSettings;\npublic static BlogSettings Settings { get { return settings; } }\n[ConfigurationProperty(\u0026ldquo;frontPagePostCount\u0026rdquo; , DefaultValue = 20 , IsRequired = false)] [IntegerValidator(MinValue = 1 , MaxValue = 100)] public int FrontPagePostCount { get { return (int)this[\u0026ldquo;frontPagePostCount\u0026rdquo;]; } set { this[\u0026ldquo;frontPagePostCount\u0026rdquo;] = value; } }\n[ConfigurationProperty(\u0026ldquo;title\u0026rdquo; , IsRequired=true)] public string Title { get { return (string)this[\u0026ldquo;title\u0026rdquo;]; } set { this[\u0026ldquo;title\u0026rdquo;] = value; } } }\nNotice that you use an indexed property to store and retrieve each property value.\nAlso not a static property named Settings for convenience.\nAdd your new configuration section to web.config (or app.config). \u0026lt;configuration\u0026gt; \u0026lt;configSections\u0026gt; \u0026lt;section name=\"BlogSettings\" type=\"Fully.Qualified.TypeName.BlogSettings, AssemblyName\" /\u0026gt; \u0026lt;/configSections\u0026gt; \u0026lt;BlogSettings frontPagePostCount=\"10\" title=\"You’ve Been Haacked\" /\u0026gt; \u0026lt;/configuration\u0026gt; And to access the new configuration using code it is as simple as:\nstring title = BlogSettings.Settings.Title; Response.Write(title); //it works!!! Here is the source code: Configuration Example\nAnother article that goes into this in a lot more details can be found on Code Project – Unraveling the Mysteries of .NET 2.0 Configuration\n","date":"10 May 2017","externalUrl":null,"permalink":"/custom-configuration-in-your-config/","section":"Articles","summary":"This post is to show how to setup a customised configuration section in your app.config or web.conifg of your .NET application\nI have written an article on this before, back in 2008, but things have moved on in the libraries and this is the latest and easiest way to create your own customised configuration.\n","title":"Custom Configuration in your config","type":"articles"},{"content":"Microsoft have release C# 7.0 and it comes with a number of new features and brings a focus on data consumption, code simplification and performance. Tuples have been around for a while but they have made them so much easier to use, which make it easy to have multiple results, and pattern matching which simplifies code that is conditional on the shape of data. But there are many other features big and small.\nTuples It is common to want to return more than one value from a method. The options available in older versions of C# are less than optimal:\nOut parameters: Use is clunky (even with the improvements described above), and they don’t work with async methods. System.Tuple\u0026lt;...\u0026gt; return types: Verbose to use and require an allocation of a tuple object. Custom-built transport type for every method: A lot of code overhead for a type whose purpose is just to temporarily group a few values. Anonymous types returned through a dynamic return type: High performance overhead and no static type checking. To do better at this, C# 7.0 adds tuple types and tuple literals:\n(string, string, string) LookupName(long id) // tuple return type { ... // retrieve first, middle and last from data storage return (first, middle, last); // tuple literal } The method now effectively returns three strings, wrapped up as elements in a tuple value.\nThe caller of the method will receive a tuple, and can access the elements individually:\nvar names = LookupName(id); WriteLine($\"found {names.Item1} {names.Item3}.\"); Item1 etc. are the default names for tuple elements, and can always be used. But they aren’t very descriptive, so you can optionally add better ones:\n(string first, string middle, string last) LookupName(long id) // tuple elements have names Now the recipient of that tuple have more descriptive names to work with:\nvar names = LookupName(id); WriteLine($\"found {names.first} {names.last}.\"); You can also specify element names directly in tuple literals:\nreturn (first: first, middle: middle, last: last); // named tuple elements in a literal Generally you can assign tuple types to each other regardless of the names: as long as the individual elements are assignable, tuple types convert freely to other tuple types.\nTuples are value types, and their elements are simply public, mutable fields. They have value equality, meaning that two tuples are equal (and have the same hash code) if all their elements are pairwise equal (and have the same hash code).\nThis makes tuples useful for many other situations beyond multiple return values. For instance, if you need a dictionary with multiple keys, use a tuple as your key and everything works out right. If you need a list with multiple values at each position, use a tuple, and searching the list etc. will work correctly.\nTuples rely on a family of underlying generic struct types called ValueTuple\u0026lt;...\u0026gt;. If you target a Framework that doesn’t yet include those types, you can instead pick them up from NuGet:\nRight-click the project in the Solution Explorer and select “Manage NuGet Packages…” Select the “Browse” tab and select “nuget.org” as the “Package source” Search for “System.ValueTuple” and install it. Pattern matching C# 7.0 introduces the notion of patterns, which, abstractly speaking, are syntactic elements that can test that a value has a certain “shape”, and extract information from the value when it does.\nExamples of patterns in C# 7.0 are:\nConstant patterns of the form c (where c is a constant expression in C#), which test that the input is equal to c Type patterns of the form T x (where T is a type and x is an identifier), which test that the input has type T, and if so, extracts the value of the input into a fresh variable x of type T Var patterns of the form var x (where x is an identifier), which always match, and simply put the value of the input into a fresh variable x with the same type as the input. This is just the beginning – patterns are a new kind of language element in C#.\nIn C# 7.0 they are enhancing two existing language constructs with patterns:\nis expressions can now have a pattern on the right hand side, instead of just a type case clauses in switch statements can now match on patterns, not just constant values In future versions of C# they are likely to add more places where patterns can be used.\nIs-expressions with patterns Here is an example of using is expressions with constant patterns and type patterns:\npublic void PrintStars(object o) { if (o is null) return; // constant pattern \"null\" if (!(o is int i)) return; // type pattern \"int i\" WriteLine(new string('*', i)); } As you can see, the pattern variables – the variables introduced by a pattern – are similar to the out variables described earlier, in that they can be declared in the middle of an expression, and can be used within the nearest surrounding scope. Also like out variables, pattern variables are mutable. We often refer to out variables and pattern variables jointly as “expression variables”.\nPatterns and Try-methods often go well together:\nif (o is int i || (o is string s \u0026amp;\u0026amp; int.TryParse(s, out i)) { /* use i */ } Switch statements with patterns We’re generalizing the switch statement so that:\nYou can switch on any type (not just primitive types) Patterns can be used in case clauses Case clauses can have additional conditions on them Here’s a simple example:\nswitch(shape) { case Circle c: WriteLine($\"circle with radius {c.Radius}\"); break; case Rectangle s when (s.Length == s.Height): WriteLine($\"{s.Length} x {s.Height} square\"); break; case Rectangle r: WriteLine($\"{r.Length} x {r.Height} rectangle\"); break; default: WriteLine(\"\u0026lt;unknown shape\u0026gt;\"); break; case null: throw new ArgumentNullException(nameof(shape)); } There are several things to note about this newly extended switch statement:\nThe order of case clauses now matters: Just like catch clauses, the case clauses are no longer necessarily disjoint, and the first one that matches gets picked. It’s therefore important that the square case comes before the rectangle case above. Also, just like with catch clauses, the compiler will help you by flagging obvious cases that can never be reached. Before this you couldn’t ever tell the order of evaluation, so this is not a breaking change of behavior. The default clause is always evaluated last: Even though the null case above comes last, it will be checked before the default clause is picked. This is for compatibility with existing switch semantics. However, good practice would usually have you put the default clause at the end. The null clause at the end is not unreachable: This is because type patterns follow the example of the current is expression and do notmatch null. This ensures that null values aren’t accidentally snapped up by whichever type pattern happens to come first; you have to be more explicit about how to handle them (or leave them for the default clause). Pattern variables introduced by a case ...: label are in scope only in the corresponding switch section.\nLiteral improvements C# 7.0 allows _ to occur as a digit separator inside number literals, I’m not a big fan of this, but I thought it worth mentioning here:\nvar d = 123_456; var x = 0xAB_CD_EF; You can put them wherever you want between digits, to improve readability. They have no effect on the value.\nAlso, C# 7.0 introduces binary literals, so that you can specify bit patterns directly instead of having to know hexadecimal notation by heart.\nvar b = 0b1010_1011_1100_1101_1110_1111; These are just a few new features of C# 7.0, to see more view Mads Torgersen blog entry\nOr watch the short video of the new features:\n","date":"24 March 2017","externalUrl":null,"permalink":"/new-features-in-c-7-0/","section":"Articles","summary":"Microsoft have release C# 7.0 and it comes with a number of new features and brings a focus on data consumption, code simplification and performance. Tuples have been around for a while but they have made them so much easier to use, which make it easy to have multiple results, and pattern matching which simplifies code that is conditional on the shape of data. But there are many other features big and small.\n","title":"New Features in C# 7.0","type":"articles"},{"content":"","date":"24 March 2017","externalUrl":null,"permalink":"/categories/visual-studio-2017/","section":"Categories","summary":"","title":"Visual Studio 2017","type":"categories"},{"content":"Microsoft have just published this great eBook which helps web developers cut right to the code scripting of environments to make all the firewall ports and get code done quickly by providing an overview of key services in the cloud, what services to use based on your needs, step by step guidance, sample code, sample applications, and a free account to get started.\nebook-a-web-developers-guide\nHere is a list of areas it covers\nWhen to Use It Moving an Existing ASP.NET Website to App Service Identity Management Scaling your Web App Caching for Performance Better Customer Experience with a CDN Detect Failures Faster Building a New Website on Azure App Service ","date":"24 March 2017","externalUrl":null,"permalink":"/a-web-developers-guide-to-help-eliminate-non-coding-tasks-and-get-code-done-faster/","section":"Articles","summary":"Microsoft have just published this great eBook which helps web developers cut right to the code scripting of environments to make all the firewall ports and get code done quickly by providing an overview of key services in the cloud, what services to use based on your needs, step by step guidance, sample code, sample applications, and a free account to get started.\n","title":"A web-developer’s guide to help eliminate non-coding tasks and get code done faster","type":"articles"},{"content":"I’ve seen from time to time applications that wrap a TRY – CATCH around some code, but do nothing except carry on. So why is this so wrong?\nAs programmers we want to write quality code that solves problems. Unfortunately, exceptions come as side effects of our code. No one likes side effects, so we soon find our own ways to get around them. I have seen some smart programmers deal with exceptions the following way:\npublic void consumeAndForgetAllExceptions(){ try { ...some code that throws exceptions } catch (Exception ex){ ex.printStacktrace(); } } What is wrong with the code above?\nOnce an exception is thrown, normal program execution is suspended and control is transferred to the catch block. The catch block catches the exception and just suppresses it. Execution of the program continues after the catch block, as if nothing had happened.\nHow about the following?\npublic void someMethod() { throw new Exception(); } This method is a blank one; it does not have any code in it. How can a blank method throw exceptions? C# does not stop you from doing this. Recently, I came across similar code where the method was declared to throw exceptions, but there was no code that actually generated that exception. When I asked the programmer, he replied “I know, it is corrupting the API, but I am used to doing it and it works.”\nThis debate goes around in circles in the C# community. I have seen several C# programmers struggle with the use of exceptions. If not used correctly, exceptions can slow down your program, as it takes memory and CPU power to create, throw, and catch exceptions. If overused, they make the code difficult to read and frustrating for the programmers using the API. We all know frustrations lead to hacks and code smells. The client code may circumvent the issue by just ignoring exceptions or throwing them.\nLet’s go back to basics and start with the definition of an Exception:\nException handling is the process of responding to the occurrence, during computation, of exceptions – anomalous or exceptional conditions requiring special processing – often changing the normal flow of program execution. It is provided by specialized programming language constructs or computer hardware mechanisms.\nThe important words here I feel is special processing something which is out of your control.\nHere is a simple example\nvar a = 0; int b; try { b = 10 / a; } catch { } So what is wrong with this?\nI call it lazy and poormans programming, one correct solution to this could be:\nvar a = 0; int b; if (a != 0) b = 10 / a; Okay this is a very simple example of abusive Exception handling, but does it really matter?\nI wrote a small benchmark test to see just what the difference is in performance. Just a simple 10,000 parallel loop count running the same code over and over again.\nI was quite overwhelmed with the performnce hit of the Exception handling, even just in this small example. The Exception handling caused the code to slow down by over 600 times.\n600 times slower code, well that does not matter if this is only happening once I hear you say…!\nThe performance is just one area, what about the extra memory that the exception is using. With a few changes to the Benchmark application am able to monitor the Garbage Collector, which although it is not a true representation of how much memory is being used it will provide a very good gauge.\nThe results of the memory useage were quite staggering\n14,416 for the programming logic 2,501,832 for the exception handing Just another reason why this is not acceptable to use the exception handler in this way.\nThis is just a short article on Excpetion Handling, but it does frustrate me when I see Exception Handling being abused.\nExceptionPerformance\n","date":"16 December 2016","externalUrl":null,"permalink":"/how-slow-are-exceptions/","section":"Articles","summary":"I’ve seen from time to time applications that wrap a TRY – CATCH around some code, but do nothing except carry on. So why is this so wrong?\nAs programmers we want to write quality code that solves problems. Unfortunately, exceptions come as side effects of our code. No one likes side effects, so we soon find our own ways to get around them. I have seen some smart programmers deal with exceptions the following way:\n","title":"How slow are Exceptions","type":"articles"},{"content":"I’m not often shocked, but when I found out that Entity Framework was not thread safe, I was horrified. I even had to buy a fellow college dinner as I lost a bet.\nNow that I knew what the problem was how can it be resolved?\nOne area I recently took some time to research is how the Unit of Work pattern is best implemented within the context of using Entity Framework. While the topic is still relatively fresh on my mind, I thought I’d use this as an opportunity to create a catalog of various approaches I’ve encountered and include some thoughts about each approach.\nUnit of Work To start, it may be helpful to give a basic definition of the Unit of Work pattern. A Unit of Work can be defined as a collection of operations that succeed or fail as a single unit. Given a series of operations which need to be executed in response to some interaction with an application, it’s often necessary to ensure that none of the operations cause side-effects if any one of them fails. This is accomplished by having participating operations respond to either a commit or rollback message indicating whether the operation performed should be completed or reverted.\nA Unit of Work can consist of different types of operations such as Web Service calls, Database operations, or even in-memory operations, however, the focus of this article will be on approaches to facilitating the Unit of Work pattern with the Entity Framework.\nWith that out of the way, let’s take a look at various approaches to facilitating the Unit of Work pattern with Entity Framework.\nImplicit Transactions The first approach to achieving a Unit of Work around a series of Entity Framework operations is to simply create an instance of a DbContext class, make changes to one or more DbSet instances, and then call SaveChanges() on the context. Entity Framework automatically creates an implicit transaction for changesets which include INSERTs, UPDATEs, and DELETEs.\nHere’s an example:\npublic Customer CreateCustomer(CreateCustomerRequest request) { Customer customer = null; using (var context = new MyStoreContext()) { customer = new Customer { FirstName = request.FirstName, LastName = request.LastName }; context.Customers.Add(customer); context.SaveChanges(); return customer; } }\nThe benefit of this approach is that a transaction is created only when necessary and is kept alive only for the duration of the SaveChanges() call. Some drawbacks to this approach, however, are that it leads to opaque dependencies and adds a bit of repetitive infrastructure code to each of your applications services.\nIf you prefer to work directly with Entity Framework then this approach may be fine for simple needs.\nTransactionScope Another approach is to use the System.Transactions.TransactionScope class provided by the .Net framework. When any of the Entity Framework operations are used which cause a connection to be opened (e.g. SaveChanges()), the connection will enlist in the ambient transaction defined by the TransactionScope class and close the transaction once the TransactionScope is successfully completed. Here’s an example of this approach:\npublic Customer CreateCustomer(CreateCustomerRequest request) { Customer customer = null; using (var transaction = new TransactionScope()) { using (var context = new MyStoreContext()) { customer = new Customer { FirstName = request.FirstName, LastName = request.LastName }; context.Customers.Add(customer); context.SaveChanges(); transaction.Complete(); }\nreturn customer; } }\nIn general, you’ll find using TransactionScope to be a good general-purpose solution for defining a Unit of Work around Entity Framework operations as it works with ADO.Net, all versions of Entity Framework, and other ORMs which provides the ability to use multiple libraries if needed. Additionally, it provides a foundation for building a more comprehensive Unit of Work pattern which would allow other types of operations to enlist in the Unit of Work.\nCaution should be exercised when using TransactionScope, however, as certain operations can implicitly escalate the transaction to a distributed transaction causing undesired overhead. For those choosing solutions involving TransactionScope, I would recommend educating yourself on how and when transactions are escalated.\nWhile you’ll find using the TransactionScope class to be a good general-purpose solution, using it directly does couple your services to a specific strategy and adds a bit of noise to your code.\nADO.Net Transactions This approach involves creating an instance of DbTransaction and instructing the participating DbContext instance to use the existing transaction:\npublic Customer CreateCustomer(CreateCustomerRequest request) { Customer customer = null; var connectionString = ConfigurationManager.ConnectionStrings[\u0026ldquo;MyStoreContext\u0026rdquo;].ConnectionString; using (var connection = new SqlConnection(connectionString)) { connection.Open(); using (var transaction = connection.BeginTransaction()) { using (var context = new MyStoreContext(connection)) { context.Database.UseTransaction(transaction); try { customer = new Customer { FirstName = request.FirstName, LastName = request.LastName }; context.Customers.Add(customer); context.SaveChanges(); } catch (Exception e) { transaction.Rollback(); throw; } }\ntransaction.Commit(); return customer; } }\nAs can be seen from the example, this approach adds quite a bit of infrastructure noise to your code. While not something I’d recommend standardizing upon, this approach provides another avenue for sharing transactions between Entity Framework and straight ADO.Net code which might prove useful in certain situations. In general, I wouldn’t recommend such an approach.\nEntity Framework Transactions The relative new-comer to the mix is the new transaction API introduced with Entity Framework 6. Here’s a basic example of it’s use:\npublic Customer CreateCustomer(CreateCustomerRequest request) { Customer customer = null; using (var context = new MyStoreContext()) { using (var transaction = context.Database.BeginTransaction()) { try { customer = new Customer { FirstName = request.FirstName, LastName = request.LastName }; context.Customers.Add(customer); context.SaveChanges(); transaction.Commit(); } catch (Exception e) { transaction.Rollback(); throw; } } }\nreturn customer; }\nThis is the approach recommended by Microsoft for achieving transactions with Entity Framework going forward. If you’re deploying applications with Entity Framework 6 and beyond, this will be your safest choice for Unit of Work implementations which only require database operation participation. Similar to a couple of the previous approaches we’ve already considered, the drawbacks of using this directly are that it creates opaque dependencies and adds repetitive infrastructure code to all of your application services. This is also a viable option, but I would recommend coupling this with other approaches we’ll look at later to improve the readability and maintainability of your application services.\nUnit of Work Repository Manager The first approach I encountered when researching how others were facilitating the Unit of Work pattern with Entity Framework was a strategy set forth by Microsoft’s guidance on the topic here. This strategy involves creating a UnitOfWork class which encapsulates an instance of the DbContext and exposes each repository as a property. Clients of repositories take a dependency upon an instance of UnitOfWork and access each repository as needed through properties on the UnitOfWork instance. The UnitOfWork type exposes a SaveChanges() method to be used when all the changes made through the repositories are to be persisted to the database. Here is an example of this approach:\npublic interface IUnitOfWork { ICustomerRepository CustomerRepository { get; } IOrderRepository OrderRepository { get; } void Save(); } public class UnitOfWork : IDisposable, IUnitOfWork { readonly MyContext _context = new MyContext(); ICustomerRepository _customerRepository; IOrderRepository _orderRepository;\npublic ICustomerRepository CustomerRepository { get { return _customerRepository ?? (_customerRepository = new CustomerRepository(_context)); } }\npublic IOrderRepository OrderRepository { get { return _orderRepository ?? (_orderRepository = new OrderRepository(_context)); } }\npublic void Dispose() { if (_context != null) { _context.Dispose(); } }\npublic void Save() { _context.SaveChanges(); } }\npublic class CustomerService : ICustomerService { readonly IUnitOfWork _unitOfWork;\npublic CustomerService(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; }\npublic void CreateCustomer(CreateCustomerRequest request) { customer = new Customer { FirstName = request.FirstName, LastName = request.LastName }; _unitOfWork.CustomerRepository.Add(customer); _unitOfWork.Save(); } }\nIt isn’t hard to imagine how this approach was conceived given it closely mirrors the typical implementation of the DbContext instance you find in Entity Framework guidance where public instances of DbSet are exposed for each aggregate root. Given this pattern is presented on the ASP.Net website and comes up as one of the first results when doing a search for “Entity Framework” and “Unit of Work”, I imagine this approach has gained some popularity among .Net developers. There are, however, a number of issues I have with this approach.\nFirst, this approach leads to opaque dependencies. Due to the fact that classes interact with repositories through the UnitOfWork instance, the client interface doesn’t clearly express the inherent business-level collaborators it depends upon (i.e. any aggregate root collections).\nSecond, this violates the Open/Closed Principle. To add new aggregate roots to the system requires modifying the UnitOfWork each time.\nThird, this violates the Single Responsibility Principle. The single responsibility of a Unit of Work implementation should be to encapsulate the behavior necessary to commit or rollback an set of operations atomically. The instantiation and management of repositories or any other component which may wish to enlist in a unit of work is a separate concern.\nLastly, this results in a nominal abstraction which is semantically coupled with Entity Framework. The example code for this approach sets forth an interface to the UnitOfWork implementation which isn’t the approach used in the aforementioned Microsoft article. Whether you take a dependency upon the interface or the implementation directly, however, the presumption of such an abstraction is to decouple the application from using Entity Framework directly. While such an abstraction might provide some benefits, it reflects Entity Framework usage semantics and as such doesn’t really decouple you from the particular persistence technology you’re using. While you could use this approach with another ORM (e.g. NHibernate), this approach is more of a reflection of Entity Framework operations (e.g. it’s flushing model) and usage patterns. As such, you probably wouldn’t arrive at this same abstraction were you to have started by defining the abstraction in terms of the behavior required by your application prior to choosing a specific ORM (i.e. following The Dependency Inversion Principle). You might even find yourself violating the Liskof Substitution Principle if you actually attempted to provide an alternate ORM implementation. Given these issues, I would advise people to avoid this approach.\nInjected Unit of Work and Repositories For those inclined to make all dependencies transparent while maintaining an abstraction from Entity Framework, the next strategy may seem the natural next step. This strategy involves creating an abstraction around the call to DbContext.SaveChanges() and requires sharing a single instance of DbContext among all the components whose operations need to participate within the underlying SaveChanges() call as a single transaction.\nHere is an example:\npublic class CustomerService : ICustomerService { readonly IUnitOfWork _unitOfWork; readonly ICustomerRepository _customerRepository; public CustomerService(IUnitOfWork unitOfWork, ICustomerRepository customerRepository) { _unitOfWork = unitOfWork; _customerRepository = customerRepository; }\npublic void CreateCustomer(CreateCustomerRequest request) { customer = new Customer { FirstName = request.FirstName, LastName = request.LastName }; _customerRepository.Add(customer); _unitOfWork.Save(); } }\nThis approach shares many of the same issues with the previous one. While it reduces a bit of infrastructure noise, it’s still semantically coupled to Entity Framework’s approach and still lacks a defined Unit of Work boundary. Additionally, it lacks clarity as to what happens when you call the SaveChanges() method. Given the Repository pattern is intended to be a virtual collection of all the entities within your system of a given type, one might suppose a method named “SaveChanges” means that you are somehow persisting any changes made to the particular entities represented by the repository (setting aside the fact that doing so is really a subversion of the pattern’s purpose). On the contrary, it really means “save all the changes made to any entities tracked by the underlying DbContext”. I would also recommend avoiding this approach.\nUnit of Work Per Request A pattern I’m a bit embarrassed to admit has been characteristic of many projects I’ve worked on in the past (though not with EF) is to create a Unit of Work implementation which is scoped to a Web Application’s Request lifetime. Using this approach, whatever method is used to facilitate a Unit of Work is configured with a DI container using a Per-HttpRequest lifetime scope and the Unit of Work boundary is opened by the first component being injected by the UnitOfWork and committed/rolled-back when the HttpRequest is disposed by the container.\nThere are a few different manifestations of this approach depending upon the particular framework and strategy you’re using, but here’s a pseudo-code example of how configuring this might look for Entity Framework with the Autofac DI container:\nbuilder.RegisterType() .As() .InstancePerRequest() .OnActivating(x =\u0026gt; { // start a transaction }) .OnRelease(context =\u0026gt; { try { // commit or rollback the transaction } catch (Exception e) { // log the exception throw; } }); public class SomeService : ISomeService { public void DoSomething() { // do some work } }\nWhile this approach eliminates the need for your services to be concerned with the Unit of Work infrastructure, the biggest issue with this is when an error happens to occur. When the application can’t successfully commit a transaction for whatever reason, the rollback occurs AFTER you’ve typically relinquished control of the request (e.g. You’ve already returned results from a controller). When this occurs, you may end up telling your customer that something happened when it actually didn’t and your client state may end up out of sync with the actual persisted state of the application.\nWhile I used this strategy without incident for some time with NHibernate, I eventually ran into a problem and concluded that the concern of transaction boundary management inherently belongs to the application-level entry point for a particular interaction with the system. This is another approach I’d recommend avoiding.\nInstantiated Unit of Work The next strategy involves instantiating a UnitOfWork implemented using either the .Net framework TransactionScope class or the transaction API introduced by Entity Framework 6 to define a transaction boundary within the application service. Here’s an example:\npublic class CustomerService : ICustomerService { readonly ICustomerRepository _customerRepository; public CustomerService(ICustomerRepository customerRepository) { _customerRepository = customerRepository; }\npublic void CreateCustomer(CreateCustomerRequest request) { using (var unitOfWork = new UnitOfWork()) { try { customer = new Customer { FirstName = request.FirstName, LastName = request.LastName }; _customerRepository.Add(customer); unitOfWork.Commit(); } catch (Exception ex) { unitOfWork.Rollback(); } } } }\nFunctionally, this is a viable approach to facilitating a Unit of Work boundary with Entity Framework. A few drawbacks, however, are that the dependency upon the Unit Of Work implementation is opaque and that it’s coupled to a specific implementation. While this isn’t a terrible approach, I would recommend other approaches discussed here which either surface any dependencies being taken on the Unit of Work infrastructure or invert the concerns of transaction management completely.\nInjected Unit of Work Factory This strategy is similar to the one presented in the Instantiated Unit of Work example, but makes its dependence upon the Unit of Work infrastructure transparent and provides a point of abstraction which allows for an alternate implementation to be provided by the factory:\npublic class CustomerService : ICustomerService { readonly ICustomerRepository _customerRepository; readonly IUnitOfWorkFactory _unitOfWorkFactory; public CustomerService(IUnitOfWorkFactory unitOfWorkFactory, ICustomerRepository customerRepository) { _customerRepository = customerRepository; _unitOfWorkFactory = unitOfWorkFactory; }\npublic void CreateCustomer(CreateCustomerRequest request) { using (var unitOfWork = _unitOfWorkFactory.Create()) { try { customer = new Customer { FirstName = request.FirstName, LastName = request.LastName }; _customerRepository.Add(customer); unitOfWork.Commit(); } catch (Exception ex) { unitOfWork.Rollback(); } } } }\nWhile I personally prefer to invert such concerns, I consider this to be a sound approach.\nAs a side note, if you decide to use this approach, you might also consider utilizing your DI Container to just inject a Func to avoid the overhead of maintaining an IUnitOfWorkFactory abstraction and implementation.\nUnit of Work ActionFilterAttribute For those who prefer to invert the Unit of Work concerns as I do, the following approach provides an easy to implement solution for those using ASP.Net MVC and/or Web API. This technique involves creating a custom Action filter which can be used to control the boundary of a Unit of Work at the Controller action level. The particular implementation may vary, but here’s a general template:\npublic class UnitOfWorkFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { // begin transaction } public override void OnActionExecuted(ActionExecutedContext filterContext) { // commit/rollback transaction } }\nThe benefits of this approach are that it’s easy to implement and that it eliminates the need for introducing repetitive infrastructure code into your application services. This attribute can be registered with the global action filters, or for the more discriminant, only placed on actions resulting in state changes to the database. Overall, this would be my recommended approach for Web applications. It’s easy to implement, simple, and keeps your code clean.\nUnit of Work Decorator A similar approach to the use of a custom ActionFilterAttribute is the creation of a custom decorator. This approach can be accomplished by utilizing a DI container to automatically decorate specific application service interfaces with a class which implements a Unit of Work boundary.\nHere is a pseudo-code example of how configuring this might look for Entity Framework with the Autofac DI container which presumes that some form of command/command-handler pattern is being utilized (e.g. frameworks like MediatR , ShortBus, etc.):\n// DI Registration builder.RegisterGenericDecorator( typeof(TransactionRequestHandler\u0026lt;\u0026gt;), // the decorator instance typeof(IRequestHandler\u0026lt;\u0026gt;), // the types to decorate \"requestHandler\", // the name of the key to decorate null); // the name of the key to this decorator public class TransactionRequestHandler : IRequestHandler where TResponse : ApplicationResponse { readonly DbContext _context; readonly IRequestHandler _decorated;\npublic TransactionRequestHandler(IRequestHandler decorated, DbContext context) { _decorated = decorated; _context = context; }\npublic TResponse Handle(TRequest request) { TResponse response;\n// Open transaction here\ntry { response = _decorated.Handle(request);\n// commit transaction\n} catch (Exception e) { //rollback transaction throw; }\nreturn response; } }\npublic class SomeRequestHandler : IRequestHandler { public ApplicationResponse Handle() { // do some work return new SuccessResponse(); } }\nWhile this approach requires a bit of setup, it provides an alternate means of facilitating the Unit of Work pattern through a decorator which can be used by other consumers of the application layer aside from just ASP.Net (i.e. Windows services, CLI, etc.) It also provides the ability to move the Unit of Work boundary closer to the point of need for those who would rather provide any error handling prior to returning control to the application service client (e.g. the Controller actions) as well as giving more control over the types of operations decorated (e.g. IQueryHandler vs. ICommandHandler). For Web applications, I’d recommend trying the custom Action Filter approach first, as it’s easier to implement and doesn’t presume upon the design of your application layer, but this is certainly a good approach if it fits your needs.\nConclusion Out of the approaches I’ve evaluated, there are several that I see as sound approaches which maintain some minimum adherence to good design practices. Of course, which approach is best for your application will be dependent upon the context of what you’re doing and to some extent the design values of your team.\nOrginal Post\n","date":"13 December 2016","externalUrl":null,"permalink":"/entity-framework-unit-of-work-patterns/","section":"Articles","summary":"I’m not often shocked, but when I found out that Entity Framework was not thread safe, I was horrified. I even had to buy a fellow college dinner as I lost a bet.\nNow that I knew what the problem was how can it be resolved?\n","title":"Entity Framework Unit of Work Patterns","type":"articles"},{"content":"Decorator pattern falls under Structural Pattern of Gang of Four (GOF) Design Patterns in .Net. Decorator pattern is used to add new functionality to an existing object without changing its structure. Hence Decorator pattern provides an alternative way to inheritance for modifying the behavior of an object. In this article, I would like to go over what the decorator pattern can do, and how it works.\nThere are some occasions in our applications when we need to create an object with some basic functionality in such a way that some extra functionality can be added to this object dynamically. For example, Lets say we need to create a Stream object to handle some data but in some cases we need this stream object to be able to encrypt the stream in some cases. So what we can do is that we can have the basic Stream object ready and then dynamically add the encryption functionality when it is needed.\nOne may also say that why not keep this encryption logic in the stream class itself and turn it on or off by using a Boolean property. But this approach will have problems like – How can we add the type custom encryption logic inside a class? Now this can be done easily by subclassing the existing class and have custom encryption logic in the derived class.\nThis is a valid solution but only when this encryption is the only functionality needed with this class. But what if there are multiple functionalities that could be added dynamically to this class and also the combination of functionalities too. If we use the subclassing approach then we will end up with derievd classes equal to the number of combination we could have for all our functionalities and the actual object.\nThis is exactly the scenario where the decorator patter can be useful. Decorators provide a flexible alternative to subclassing for extending functionality.”\nBefore looking into the details of decorator pattern let us go ahead, let’s have a look at what this pattern is and then see the class diagram of this pattern and see what each class is responsible for.\nWhat is Decorator Pattern Decorator pattern is used to add new functionality to an existing object without changing its structure.\nThis pattern creates a decorator class which wraps the original class and add new behaviors/operations to an object at run-time.\nStill none the wiser? Let’s look at a diagram to help you picture the pattern.\nDecorator Pattern – UML Diagram \u0026amp; Implementation The UML class diagram for the implementation of the decorator design pattern is given below:\nThe classes, interfaces and objects in the above UML class diagram are as follows:\nComponent This is an interface containing members that will be implemented by ConcreteClass and Decorator.\nConcreteComponent This is a class which implements the Component interface.\nDecorator This is an abstract class which implements the Component interface and contains the reference to a Component instance. This class also acts as base class for all decorators for components.\nConcreteDecorator This is a class which inherits from Decorator class and provides a decorator for components.\nC# – Implementation Code public interface Component { void Operation(); } public class ConcreteComponent : Component { public void Operation() { Console.WriteLine(\u0026ldquo;Component Operation\u0026rdquo;); } }\npublic abstract class Decorator : Component { private Component _component;\npublic Decorator(Component component) { _component = component; }\npublic virtual void Operation() { _component.Operation(); } }\npublic class ConcreteDecorator : Decorator { public ConcreteDecorator(Component component) : base(component) { }\npublic override void Operation() { base.Operation(); Console.WriteLine(\u0026ldquo;Override Decorator Operation\u0026rdquo;); } }\nDecorator Pattern – Example Who is what? The classes, interfaces and objects in the above class diagram can be identified as follows:\nVehicle – Component Interface. HondaCity- ConcreteComponent class. VehicleDecorator- Decorator Class. Special Offer- ConcreteDecorator class. C# – Sample Code /// \u0026lt;summary\u0026gt; /// The 'Component' interface /// \u0026lt;/summary\u0026gt; public interface Vehicle { string Make { get; } string Model { get; } double Price { get; } } /// \u0026lt;summary\u0026gt; /// The \u0026lsquo;ConcreteComponent\u0026rsquo; class /// \u0026lt;/summary\u0026gt; public class HondaCity : Vehicle { public string Make { get { return \u0026ldquo;HondaCity\u0026rdquo;; } }\npublic string Model { get { return \u0026ldquo;CNG\u0026rdquo;; } }\npublic double Price { get { return 1000000; } } }\n/// \u0026lt;summary\u0026gt; /// The \u0026lsquo;Decorator\u0026rsquo; abstract class /// \u0026lt;/summary\u0026gt; public abstract class VehicleDecorator : Vehicle { private Vehicle _vehicle;\npublic VehicleDecorator(Vehicle vehicle) { _vehicle = vehicle; }\npublic string Make { get { return _vehicle.Make; } }\npublic string Model { get { return _vehicle.Model; } }\npublic double Price { get { return _vehicle.Price; } }\n}\n/// \u0026lt;summary\u0026gt; /// The \u0026lsquo;ConcreteDecorator\u0026rsquo; class /// \u0026lt;/summary\u0026gt; public class SpecialOffer : VehicleDecorator { public SpecialOffer(Vehicle vehicle) : base(vehicle) { }\npublic int DiscountPercentage { get; set; } public string Offer { get; set; }\npublic new double Price { get { double price = base.Price; int percentage = 100 - DiscountPercentage; return Math.Round((price * percentage) / 100, 2); } }\n}\n/// \u0026lt;summary\u0026gt; /// Decorator Pattern Demo /// \u0026lt;/summary\u0026gt; class Program { static void Main(string[] args) { // Basic vehicle HondaCity car = new HondaCity();\nConsole.WriteLine(\u0026ldquo;Honda City base price are : {0}\u0026rdquo;, car.Price);\n// Special offer SpecialOffer offer = new SpecialOffer(car); offer.DiscountPercentage = 25; offer.Offer = \u0026ldquo;25 % discount\u0026rdquo;;\nConsole.WriteLine(\u0026quot;{1} @ Diwali Special Offer and price are : {0} \u0026ldquo;, offer.Price, offer.Offer);\nConsole.ReadKey();\n} }\nDecorator Pattern Demo – Output When to use it? Add additional state or behavior to an object dynamically.\nMake changes to some objects in a class without affecting others.\nOriginal Article by Shailendra Chauhan\nHere is a sample application Decorator Pattern\n","date":"12 December 2016","externalUrl":null,"permalink":"/decorator-pattern/","section":"Articles","summary":"Decorator pattern falls under Structural Pattern of Gang of Four (GOF) Design Patterns in .Net. Decorator pattern is used to add new functionality to an existing object without changing its structure. Hence Decorator pattern provides an alternative way to inheritance for modifying the behavior of an object. In this article, I would like to go over what the decorator pattern can do, and how it works.\n","title":"Decorator Pattern","type":"articles"},{"content":"I’ve been racking my brains as the sorting on the Kendo Grid is pretty good, only that I need to be able to not sort in the order that is being displayed. An example would be numbers written out in full and you want them in number sort order.\n@(Html.Kendo().Grid\u0026lt;Number\u0026gt;() .Name(\"grid\") .Columns(columns =\u0026gt; { columns.Bound(c =\u0026gt; c.Id); columns.Bound(c =\u0026gt; c.Item); }) .Sortable() .DataSource(dataSource =\u0026gt; dataSource .Ajax() .Read(read =\u0026gt; read.Action(\"Numbers_Read\", \"Home\")) ) ) Here is the list not in any order, but it does have a sortorder column\nprivate static List\u0026lt;Number\u0026gt; GetNumbers() { List\u0026lt;Number\u0026gt; numbers = new List\u0026lt;Number\u0026gt;(); numbers.Add(new Number() { Id = 1, Item = \u0026ldquo;one\u0026rdquo;, SortOrder = \u0026ldquo;1\u0026rdquo; });\nnumbers.Add(new Number() { Id = 2, Item = \u0026ldquo;three\u0026rdquo;, SortOrder = \u0026ldquo;3\u0026rdquo; });\nnumbers.Add(new Number() { Id = 3, Item = \u0026ldquo;six\u0026rdquo;, SortOrder = \u0026ldquo;6\u0026rdquo; }); numbers.Add(new Number() { Id = 4, Item = \u0026ldquo;two\u0026rdquo;, SortOrder = \u0026ldquo;2\u0026rdquo; }); numbers.Add(new Number() { Id = 5, Item = \u0026ldquo;five\u0026rdquo;, SortOrder = \u0026ldquo;5\u0026rdquo; }); numbers.Add(new Number() { Id = 6, Item = \u0026ldquo;seven\u0026rdquo;, SortOrder = \u0026ldquo;7\u0026rdquo; }); numbers.Add(new Number() { Id = 7, Item = \u0026ldquo;four\u0026rdquo;, SortOrder = \u0026ldquo;4\u0026rdquo; }); return numbers; }\nand now for the magic, when the request is coming back into the controller action we check to see what is being requested and then change it to another hidden column, this way it retains all the functionality of the Kendo Grid and it just works….!\npublic ActionResult Numbers_Read([DataSourceRequest]DataSourceRequest request) { List\u0026lt;Number\u0026gt; numbers = GetNumbers(); foreach (var sort in request.Sorts) { // Find the sort member you need a custom sort for and change it to the custom column if (sort.Member.ToLowerInvariant() == \u0026ldquo;item\u0026rdquo;) { sort.Member = \u0026ldquo;SortOrder\u0026rdquo;; } } return Json(numbers.ToDataSourceResult(request), JsonRequestBehavior.AllowGet); }\nI have created this sample Kendo Grid project so you can see how it is all done.\nkendo_grid\n","date":"8 December 2016","externalUrl":null,"permalink":"/kendo-grid-custom-sort-order/","section":"Articles","summary":"I’ve been racking my brains as the sorting on the Kendo Grid is pretty good, only that I need to be able to not sort in the order that is being displayed. An example would be numbers written out in full and you want them in number sort order.\n","title":"Kendo Grid custom sort order","type":"articles"},{"content":"","date":"8 December 2016","externalUrl":null,"permalink":"/categories/mvc/","section":"Categories","summary":"","title":"MVC","type":"categories"},{"content":"It’s important for a team to have a single coding standard for each language to avoid several problems:\nA lack of standards can make your code unreadable. Disagreement over standards can cause check-in wars between developers. Seeing different standards in the same class can be extremely irritating. UncleBob wrote this:\nOn coding standards:\nLet them evolve during the first few iterations. Let them be team specific instead of company specific. Don’t write them down if you can avoid it. Rather, let the code be the way the standards are captured. Don’t legislate good design. (e.g. don’t tell people not to use goto)\nMake sure everyone knows that the standard is about communication, and nothing else. After the first few iterations, get the team together to decide. Original article\n","date":"5 December 2016","externalUrl":null,"permalink":"/uncle-bob-on-coding-standards/","section":"Articles","summary":"It’s important for a team to have a single coding standard for each language to avoid several problems:\nA lack of standards can make your code unreadable. Disagreement over standards can cause check-in wars between developers. Seeing different standards in the same class can be extremely irritating. UncleBob wrote this:\n","title":"Uncle Bob On Coding Standards","type":"articles"},{"content":" Code metrics is a set of software measures that provide developers better insight into the code they are developing. By taking advantage of code metrics, developers can understand which types and/or methods should be reworked or more thoroughly tested.\nWhat is the preferred score range for the code metrics calculation for the following\nMaintainability Index Cyclomatic Complexity Depth of Inheritance class Coupling The theoretically optimal values are:\nMaintainability index: 100. Higher values indicate better maintainability. Cyclomatic complexity: 1. The number of different paths that code can take. Depth of inheritance: 1. The number of class definitions above this one in the inheritance tree, not including interfaces. Class coupling: 0. Number of other entities this entity is dependent on. There are no hard and fast “good” ranges, though it’s possible to make some general statements.\nHaving high per-method cyclomatic complexity suggests a method is getting too complicated. Having an inheritance depth more than about 3 or 4 (of your own classes, not the framework’s) is a trouble sign that you may be unnecessarily representing abstract relationships that aren’t really in your software’s domain. Low class coupling is in general better, but sometimes it’s unavoidable. To the extent possible, you should definitely minimise the dependency between namespaces, since there’s much less reason for dependencies here. A project could only reach all four values simultaneously by essentially doing nothing and being useless: software that does nothing and depends on nothing is certainly maintainable, but not a very good use of client dollars.\nTherefore, all complexity is a trade-off: additional so-called inherent complexity encodes more sophistication into the program, allowing it to expand the feature set. What you would like to avoid is accidental complexity introduced by a poor or deficient implementation.\n","date":"30 November 2016","externalUrl":null,"permalink":"/code-metrics-what-do-they-mean/","section":"Articles","summary":" Code metrics is a set of software measures that provide developers better insight into the code they are developing. By taking advantage of code metrics, developers can understand which types and/or methods should be reworked or more thoroughly tested.\n","title":"Code Metrics what do they mean?","type":"articles"},{"content":"","date":"30 November 2016","externalUrl":null,"permalink":"/categories/visual-studio-2015/","section":"Categories","summary":"","title":"Visual Studio 2015","type":"categories"},{"content":"","date":"30 November 2016","externalUrl":null,"permalink":"/categories/ioc/","section":"Categories","summary":"","title":"IoC","type":"categories"},{"content":"So which is the fastest at different IoC Lifestyles.\nIn this benchmark we will be running, head to had, with Castle Windsor, Ninject, Spring.NET, Unity, Microsoft DI, AutoFac, and Structure Map.\nHere is a working project, this uses NuGet to included the packages, so as time goes on you may find the packages go out of date, so you’ll need to refactor the code to work with the next packages.\nI’m using a Parallel test as this represents a closer real life example of how the containers will be used.\nioc-benchmark\n","date":"30 November 2016","externalUrl":null,"permalink":"/ioc-benchmark/","section":"Articles","summary":"So which is the fastest at different IoC Lifestyles.\nIn this benchmark we will be running, head to had, with Castle Windsor, Ninject, Spring.NET, Unity, Microsoft DI, AutoFac, and Structure Map.\nHere is a working project, this uses NuGet to included the packages, so as time goes on you may find the packages go out of date, so you’ll need to refactor the code to work with the next packages.\n","title":"IoC Benchmark","type":"articles"},{"content":"Scrum and Kanban are two terms that are often (incorrectly) used interchangeably or thought to be two sides of the same coin. In reality, there are significant differences between these two Agile methodologies. Understanding these differences is key to choosing the path that will work best for your environment. In a nutshell, what is Scrum? Without getting too detailed, Scrum is a tool used to organise work into small, manageable pieces that can be completed by a cross-functional team within a prescribed time period (called a sprint, generally 2-4 weeks long). To plan, organise, administer, and optimise this process, Scrum relies on at least three prescribed roles: the Product Owner (responsible for initial planning, prioritising, and communication with the rest of the company), the Scrum Master (responsible for overseeing the process during each sprint), and the Team Members (responsible to carry out the purpose of each sprint, such as producing software code.) Another common tool used by scrum teams is the Scrum Board – a visual representation of the work flow, broken down into manageable chunks called “stories”, with each story moved along the board from the “backlog” (the to-do list), into work-in-progress (WIP), and on to completion.\nWhat is Kanban? Again, scratching the surface, Kanban is also a tool used to organise work for the sake of efficiency. Like Scrum, Kanban encourages work to be broken down into manageable chunks and uses a Kanban Board (very similar to the Scrum Board) to visualise that work as it progresses through the work flow. Where Scrum limits the amount of time allowed to accomplish a particular amount of work (by means of sprints), Kanban limits the amount of work allowed in any one condition (only so many tasks can be ongoing, only so many can be on the to-do list.)\nHow are Scum and Kanban the same? Both Scrum and Kanban allow for large and complex tasks to be broken down and completed efficiently. Both place a high value on continual improvement, optimisation of the work and the process. And both share the very similar focus on a highly visible work flow that keeps all team members in the loop on WIP and what’s to come.\nHow are Scrum and Kanban different? As alluded to above, there are a number of differences in both the philosophy behind and the practical application of Scrum and Kanban. While the individual differences are many, they can be grouped into the following three buckets:\nScheduling Iteration Cadence Scrum processes place heavy emphasis on schedule. The scrum team is provided with a prioritised list of story points that need to be completed to deliver a shippable product. The team must decide how many of the points they feel can be completed within one sprint. Anything outside the scope they commit to must wait for the next sprint. Optimally, an efficient scrum team will quickly learn their capabilities over the course of several sprints and their estimates will improve and be optimised as time goes on. Then, every two weeks (or however long their sprint is) the team produces a shippable product, carries out a retrospective to discuss optimising the process, and moves into the next sprint. This iterative process is designed to allow for accurate estimations of work flow and effective management of multiple projects. On a Kanban team, there are no required time boxes or iterations. While the Kanban method is iterative in nature, the continual improvement is expected to occur in an evolutionary fashion as work is continually completed. The limitations placed on various conditions in the work flow will be regulated early in a team’s (or organisation’s) use of Kanban until an optimal set of limits is arrived at to keep the flow steady and efficient.\nRoles and Responsibilities On scrum teams, there are at least three roles that must be assigned in order to effectively process the work: the Product Owner, Scrum Master, and Team Members. Each role has its own set of responsibilities, and they must work together to achieve an orderly and efficient balance. The scrum team itself also must be cross-functional, which is to say that one team must have all the resources necessary to complete the entire sprint’s work. Under Kanban, no set roles are prescribed. Practically speaking, it makes sense for someone to serve as a project manager or supervisor, especially for larger more complex Kanban projects, but the roles should theoretically evolve with the needs of the project and the organisation. A Kanban team is not required to be cross-functional since the Kanban work flow is intended to be used by any and all teams involved in the project. Therefore, a team of specialists and a separate team of generalists may be working on different aspects of the same Kanban project from the same board, and that’s okay.\nThe Board While very similar, the Scrum Board and Kanban Board are different animals. On a Scrum board, the columns are labelled to reflect periods in the work flow beginning with the sprint backlog and ending with whatever fulfils the team’s definition of done. All the stories added to the board at the beginning of each sprint should be found in the final column at the end of that sprint or the sprint was unsuccessful. After the sprint retrospective, the board is cleared and prepped for the next sprint. On a Kanban board, the columns are likewise labelled to show work flow states, but with one vital difference: they also publish the maximum number of stories allowed in each column at any one time. This enforces the team-determined limitations Kanban prescribes for each condition. Since each column has a limited number of allowed stories and there are no required time boxes (such as sprint length), there is no reason to reset the Kanban board as work progresses. It will continue to flow for as long as the project continues, with new stories being added as the need arises, and completed stories being re-evaluated should it be necessary.\nWhich is better for your needs? There’s really no way to answer that question for you in this article. Both Scrum and Kanban are powerful, proven process tools that can vastly improve your project management. The best option is to become familiar with both of them and experiment with various aspects of both in your production environment. Creating a hybrid of both is perfectly acceptable if that works best for you. For more information about Scrum and Kanban, take a peek inside this webinar and learn how to incorporate these approaches into your overall strategy.\n","date":"29 November 2016","externalUrl":null,"permalink":"/differences-between-scrum-and-kanban/","section":"Articles","summary":"Scrum and Kanban are two terms that are often (incorrectly) used interchangeably or thought to be two sides of the same coin. In reality, there are significant differences between these two Agile methodologies. Understanding these differences is key to choosing the path that will work best for your environment. In a nutshell, what is Scrum? Without getting too detailed, Scrum is a tool used to organise work into small, manageable pieces that can be completed by a cross-functional team within a prescribed time period (called a sprint, generally 2-4 weeks long). To plan, organise, administer, and optimise this process, Scrum relies on at least three prescribed roles: the Product Owner (responsible for initial planning, prioritising, and communication with the rest of the company), the Scrum Master (responsible for overseeing the process during each sprint), and the Team Members (responsible to carry out the purpose of each sprint, such as producing software code.) Another common tool used by scrum teams is the Scrum Board – a visual representation of the work flow, broken down into manageable chunks called “stories”, with each story moved along the board from the “backlog” (the to-do list), into work-in-progress (WIP), and on to completion.\n","title":"Differences between Scrum and Kanban","type":"articles"},{"content":"Factory Support Facility allows using factories to create components. This is beneficial when you want to make available as services components that do not have accessible constructor, or that you don’t instantiate, like HttpContext.\nPrefer UsingFactoryMethod over this facility: while the facility provides programmatic API it is deprecated and its usage is discouraged and won’t be discussed here. Recommended approach is to use UsingFactoryMethod method of fluent registration API to create components. This limits the usefulness of the facility to XML-driven and legacy scenarios.\nUsingFactoryMethod does not require this facility anymore: In older versions of Windsor (up to and including version 2.1) UsingFactoryMethod method in the fluent API discussed above required this facility to be active in the container. That was later changed and there’s no such dependency anymore.\nUsing factories from configuration In addition to code, the facility uses XML configuration. You can register the facility in the standard facilities section of Windsor’s config:\nJust install the facility and add the proper configuration.\n\u0026lt;configuration\u0026gt; \u0026lt;facilities\u0026gt; \u0026lt;facility id=\"factory.support\" type=\"Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Facilities.FactorySupport\" /\u0026gt; \u0026lt;/facilities\u0026gt; \u0026lt;/configuration\u0026gt; Configuration Schema Broadly speaking facility exposes the following scheme, with two kinds of supported factories: accessors and methods\n\u0026lt;components\u0026gt; \u0026lt;component id=\"mycomp1\" instance-accessor=\"Static accessor name\" /\u0026gt; \u0026lt;component id=\"factory1\" /\u0026gt; \u0026lt;component id=\"mycomp2\" factoryId=\"factory1\" factoryCreate=\"Create\" /\u0026gt; \u0026lt;/components\u0026gt; Accessor example Given the following singleton class:\npublic class SingletonWithAccessor { private static readonly SingletonWithAccessor instance = new SingletonWithAccessor(); private SingletonWithAccessor() { }\npublic static SingletonWithAccessor Instance { get { return instance; } } }\nYou may expose its instance to the container through the following configuration:\n\u0026lt;components\u0026gt; \u0026lt;component id=\"mycomp1\" type=\"Company.Components.SingletonWithAccessor, Company.Components\" instance-accessor=\"Instance\" /\u0026gt; \u0026lt;/components\u0026gt; Using it:\nvar comp = container.Resolve\u0026lt;SingletonWithAccessor\u0026gt;(\"mycomp1\"); Factory example Given the following component and factory classes:\npublic class MyComp { internal MyComp() { } \u0026hellip; }\npublic class MyCompFactory { public MyComp Create() { return new MyComp(); } }\nYou may expose its instance to the container through the following configuration:\n\u0026lt;components\u0026gt; \u0026lt;component id=\"mycompfactory\" type=\"Company.Components.MyCompFactory, Company.Components\"/\u0026gt; \u0026lt;component id=\"mycomp\" type=\"Company.Components.MyComp, Company.Components\" factoryId=\"mycompfactory\" factoryCreate=\"Create\" /\u0026gt; \u0026lt;/components\u0026gt; Using it:\nvar comp = container.Resolve\u0026lt;MyComp\u0026gt;(\"mycomp\"); Factory with parameters example Given the following component and factory classes:\npublic class MyComp { internal MyComp(String storeName, IDictionary props) { } \u0026hellip; }\npublic class MyCompFactory { public MyComp Create(String storeName, IDictionary props) { return new MyComp(storeName, props); } }\nYou may expose its instance to the container through the following configuration:\n\u0026lt;components\u0026gt; \u0026lt;component id=\"mycompfactory\" type=\"Company.Components.MyCompFactory, Company.Components\"/\u0026gt; \u0026lt;component id=\"mycomp\" type=\"Company.Components.MyComp, Company.Components\" factoryId=\"mycompfactory\" factoryCreate=\"Create\"\u0026gt; \u0026lt;parameters\u0026gt; \u0026lt;storeName\u0026gt;MyStore\u0026lt;/storeName\u0026gt; \u0026lt;props\u0026gt; \u0026lt;dictionary\u0026gt; \u0026lt;entry key=\"key1\"\u0026gt;item1\u0026lt;/entry\u0026gt; \u0026lt;entry key=\"key2\"\u0026gt;item2\u0026lt;/entry\u0026gt; \u0026lt;/dictionary\u0026gt; \u0026lt;/props\u0026gt; \u0026lt;/parameters\u0026gt; \u0026lt;/component\u0026gt; \u0026lt;/components\u0026gt; Using it:\nvar comp = container.Resolve\u0026lt;MyComp\u0026gt;(\"mycomp\"); Factory using auto-wire example If your factory request as parameter some other component instance, this facility will be able to resolve it without your aid:\npublic class MyComp { internal MyComp(IMyService serv) { } \u0026hellip; }\npublic class MyCompFactory { public MyComp Create(IMyService service) { return new MyComp(service); } }\nYou may expose its instance to the container through the following configuration:\n\u0026lt;facilities\u0026gt; \u0026lt;facility id=\"factorysupport\" type=\"Castle.Facilities.FactorySupport.FactorySupportFacility, Castle.Facilities.FactorySupport\"/\u0026gt; \u0026lt;/facilities\u0026gt; \u0026lt;components\u0026gt; \u0026lt;component id=\u0026ldquo;myservice\u0026rdquo; service=\u0026ldquo;SomethingElse.IMyService\u0026rdquo; type=\u0026ldquo;Company.Components.MyServiceImpl, Company.Components\u0026rdquo; /\u0026gt; \u0026lt;component id=\u0026ldquo;mycompfactory\u0026rdquo; type=\u0026ldquo;Company.Components.MyCompFactory, Company.Components\u0026rdquo; /\u0026gt; \u0026lt;component id=\u0026ldquo;mycomp\u0026rdquo; type=\u0026ldquo;Company.Components.MyComp, Company.Components\u0026rdquo; factoryId=\u0026ldquo;mycompfactory\u0026rdquo; factoryCreate=\u0026ldquo;Create\u0026rdquo; /\u0026gt; \u0026lt;/components\u0026gt;\nUsing it:\nvar comp = container.Resolve\u0026lt;MyComp\u0026gt;(\"mycomp\"); ","date":"28 November 2016","externalUrl":null,"permalink":"/factory-support-facility/","section":"Articles","summary":"Factory Support Facility allows using factories to create components. This is beneficial when you want to make available as services components that do not have accessible constructor, or that you don’t instantiate, like HttpContext.\nPrefer UsingFactoryMethod over this facility: while the facility provides programmatic API it is deprecated and its usage is discouraged and won’t be discussed here. Recommended approach is to use UsingFactoryMethod method of fluent registration API to create components. This limits the usefulness of the facility to XML-driven and legacy scenarios.\n","title":"Factory Support Facility","type":"articles"},{"content":"Inversion of Control (IoC) is quite a big step for some developers, but the benefits once implemented are huge. With the applications performance, maintainability, unit testing and more importantly separation of concerns, just to name a few.\nBasic Registration The starting point for registering anything in the container is the container’s Register method, with has one or more IRegistration objects as parameter. The simplest way to create those objects is using the static Castle.MicroKernel.Registration.Component class. Its For method returns a ComponentRegistration that you can use to further configure the registration.\nIsolate your registration code: It is a recommended practice to keep your registration code in a dedicated class(es) implementing IWindsorInstaller.\nInstall infrastructure components first: Some components may require a facility or other extension to the core container to be registered properly. As such it is recommended that you always register your facilities, custom subsystems, Component model creation contributors etc before you start registering your components.\nTo register a type in the container container.Register( Component.For(MyServiceImpl) ); This will register type MyServiceImpl as service MyServiceImpl with default lifestyle (Singleton).\nTo register a type as non-default service container.Register( Component.For(IMyService).ImplementedBy(MyServiceImpl)); Note that For and ImplementedBy also have non-generic overloads.\n// Same result as example above. container.Register(Component.For(typeof(IMyService)) .ImplementedBy(typeof(MyServiceImpl)) ); Services and Components: You can find more information about services and components here.\nTo register a generic type Suppose you have a IRepository\u0026lt;TEntity\u0026gt; interface, with NHRepository\u0026lt;TEntity\u0026gt; as the implementation.\nYou could register a repository for each entity class, but this is not needed.\n// Registering a repository for each entity is not needed. container.Register( Component.For\u0026lt;IRepository\u0026lt;Customer\u0026gt;\u0026gt;() .ImplementedBy\u0026lt;NHRepository\u0026lt;Customer\u0026gt;\u0026gt;(), Component.For\u0026lt;IRepository\u0026lt;Order\u0026gt;\u0026gt;() .ImplementedBy\u0026lt;NHRepository\u0026lt;Order\u0026gt;\u0026gt;(), // and so on... ); One IRepository\u0026lt;\u0026gt; (so called open generic type) registration, without specifying the entity, is enough.\n// Does not work (compiler won't allow it): container.Register( Component.For\u0026lt;IRepository\u0026lt;\u0026gt;\u0026gt;() .ImplementedBy\u0026lt;NHRepository\u0026lt;\u0026gt;\u0026gt;() ); Doing it like this however is not legal, and the above code would not compile. Instead you have to use typeof()\n// Use typeof() and do not specify the entity: container.Register( Component.For(typeof(IRepository\u0026lt;\u0026gt;)) .ImplementedBy(typeof(NHRepository\u0026lt;\u0026gt;)) ); Configuring component’s lifestyle container.Register( Component.For\u0026lt;IMyService\u0026gt;() .ImplementedBy\u0026lt;MyServiceImpl\u0026gt;() .LifeStyle.Transient ); When the lifestyle is not set explicitly, the default Singleton lifestyle will be used.\nRegister more components for the same service You can do this simply by having more registrations for the same service.\ncontainer.Register( Component.For\u0026lt;IMyService\u0026gt;().ImplementedBy\u0026lt;MyServiceImpl\u0026gt;(), Component.For\u0026lt;IMyService\u0026gt;().ImplementedBy\u0026lt;OtherServiceImpl\u0026gt;() ); When a component has a dependency on IMyService, it will by default get the IMyService that was registered first (in this case MyServiceImpl).\nIn Windsor first one wins: In Castle, the default implementation for a service is the first registered implementation.\nYou can force the later-registered component to become the default instance via the method IsDefault.\ncontainer.Register( Component.For\u0026lt;IMyService\u0026gt;().ImplementedBy\u0026lt;MyServiceImpl\u0026gt;(), Component.For\u0026lt;IMyService\u0026gt;().Named(\"OtherServiceImpl\") .ImplementedBy\u0026lt;OtherServiceImpl\u0026gt;().IsDefault() ); In the above example, any component that has a dependency on IMyService, will by default get an instance of OtherServiceImpl, even though it was registered later.\nOf course, you can override which implementation is used by a component that needs it. This is done with service overrides.\nWhen you explicitly call container.Resolve\u0026lt;IMyService\u0026gt;() (without specifying the name), the container will also return the first registered component for IMyService (MyServiceImpl in the above example).\nProvide unique names for duplicated components: If you want to register the same implementation more than once, be sure to provide different names for the registered components.\nUsing a delegate as component factory You can use a delegate as a lightweight factory for a component:\ncontainer.Register( Component.For\u0026lt;IMyService\u0026gt;() .UsingFactoryMethod( () =\u0026gt; MyLegacyServiceFactory.CreateMyService()) ); UsingFactoryMethod method has two more overloads, which can provide you with access to kernel, and creation context if needed.\nExample of UsingFactoryMethod with kernel overload (Converter)\ncontainer.Register( Component.For\u0026lt;IMyFactory\u0026gt;().ImplementedBy\u0026lt;MyFactory\u0026gt;(), Component.For\u0026lt;IMyService\u0026gt;() .UsingFactoryMethod(kernel =\u0026gt; kernel.Resolve\u0026lt;IMyFactory\u0026gt;().Create()) ); In addition to UsingFactoryMethod method, there’s a UsingFactory method. (without the “method” suffix 🙂 ). It can be regarded as a special version of UsingFactoryMethod method, which resolves an existing factory from the container, and lets you use it to create instance of your service.\ncontainer.Register( Component.For\u0026lt;User\u0026gt;().Instance(user), Component.For\u0026lt;AbstractCarProviderFactory\u0026gt;(), Component.For\u0026lt;ICarProvider\u0026gt;() .UsingFactory((AbstractCarProviderFactory f) =\u0026gt; f.Create(container.Resolve\u0026lt;User\u0026gt;())) ); Avoid UsingFactory: It is advised to use UsingFactoryMethod, and to avoid UsingFactory when creating your services via factories. UsingFactory will be obsoleted/removed in future releases.\nOnCreate It is sometimes needed to either inspect or modify created instance, before it is used. You can use OnCreate method to do this\ncontainer.Register( Component.For\u0026lt;IService\u0026gt;() .ImplementedBy\u0026lt;MyService\u0026gt;() .OnCreate((kernel, instance) =\u0026gt; instance.Name += \"a\") ); The method has two overloads. One that works with a delegate to which an IKernel and newly created instance are passed. Another only takes the newly created instance.\nOnCreate works only for components created by the container: This method is not called for components where instance is provided externally (like when using Instance method). It is called only for components created by the container. This also includes components created via certain facilities (Remoting Facility, Factory Support Facility)\nA good source of reference is the Castle Windsor documentation, which can be found here:\nhttps://github.com/castleproject/Windsor/tree/master/docs\nHere is a sample project with examples and a MVC application showing how it all works\ncastle windsor\n","date":"28 November 2016","externalUrl":null,"permalink":"/registering-components-for-ioc/","section":"Articles","summary":"Inversion of Control (IoC) is quite a big step for some developers, but the benefits once implemented are huge. With the applications performance, maintainability, unit testing and more importantly separation of concerns, just to name a few.\n","title":"Registering components for IoC","type":"articles"},{"content":"I do love dependency injection, but many developers still seem to miss the point and the reason for having it. If you’re only using it on a small scale, you don’t really need any tools to use the technique. But once you’re used to this design technique, you’ll quickly start using it in many places of your code. If you do, it quickly becomes cumbersome to deal with the real instances of your runtime dependencies manually. This is where tools like Inversion Of Control (IoC) containers come in to play. There are a few solid containers available for the .NET world, and even Microsoft has released their own container. Basically, what the IoC container does for you, is take care of providing dependencies to components in a flexible and customizable way. It allows clients to remain completely oblivious to the dependencies of components they use. This makes it easy to change components without having to modify client code. Not to mention the fact that your components are a lot easier to test, since you can simply inject fake dependencies during your tests.\nLets get do to looking at a sample. Suppose we have a class called OrderRepository which exposes methods such as GetById, GetAll, FindOne, FindMany and Store. Obviously, the OrderRepository has a dependency on a class that can actually communicate with some kind of physical datastore, either a database or an xml file or whatever. Either way, it needs another object to access the Order data. Suppose we have an OrderAccessor class which implements an IOrderAccessor interface. The interface declares all the methods we need to retrieve or store our Orders. So our OrderRepository would need to communicate with an object that implements the IOrderAccessor interface. Instead of letting the OrderRepository instantiate that object itself, it will receive it as a parameter in it’s constructor:\nprivate readonly IOrderDataAccessor _accessor;\npublic OrderRepository(IOrderDataAccessor accessor)\n{\n_accessor = accessor;\n}\nThis makes it easy to test the OrderRepository class, and it’s also easy to make it use different implementations of IOrderDataAccessor later on, should we need to. Now obviously, you really don’t want to do this when you need to instantiate the OrderRepository in your production code:\nOrderRepository repo = new OrderRepository(new OrderDataAccessor());\nAs a consumer of the OrderRepository, you shouldn’t need to know what its dependencies are and you most certainly shouldn’t need to pass the right dependencies into the constructor. Instead, you just want a valid instance of OrderRepository. You really don’t care how it was constructed, which dependencies it has and how they’re provided. You just need to be able to use it. That’s all. This is where the IoC container comes in to help you. Suppose we wrap the IoC container in a Container class that has a few static methods to help you with instantiating instances of types. We could then do this:\nOrderRepository repository = Container.Resolve\u0026lt;OrderRepository\u0026gt;();\nThat would leave you with a valid OrderRepository instance… one that has a usable IOrderDataAccessor but you don’t even know about it, nor do you care how it got there. In other words, you can use the OrderRepository without knowing anything about its underlying implementation.\nLet’s take a look at the implementation of the Container class:\npublic static class Container\n{\nprivate static readonly IWindsorContainer _container;\nstatic Container()\n{\n_container = new WindsorContainer();\n_container.Register(Component.For\u0026lt;IOrderDataAccessor\u0026gt;).ImplementedBy\u0026lt;OrderDataAccessor\u0026gt;());\n_container.Register(Component.For\u0026lt;OrderRepository\u0026gt;).ImplementedBy\u0026lt;OrderRepository\u0026gt;());\n}\npublic static T Resolve\u0026lt;T\u0026gt;()\n{\nreturn _container.Resolve\u0026lt;T\u0026gt;();\n}\n}\nIt just uses a static instance of Windor’s Container and it registers the types we need… let’s examine the following line:\n_container.Register(Component.For\u0026lt;IOrderDataAccessor\u0026gt;).ImplementedBy\u0026lt;OrderDataAccessor\u0026gt;());\nthis basically sets up the container to return a new instance of OrderDataAccessor whenever an instance of IOrderDataAcessor is requested.\nWe still have to make sure the Windsor container knows about the OrderRepository class by adding it as a known component like this:\n_container.Register(Component.For\u0026lt;OrderRepository\u0026gt;).ImplementedBy\u0026lt;OrderRepository\u0026gt;());\nBy doing this, the Windsor container will inspect the type (in this case, OrderRepository) and it will see that its constructor requires an IOrderDataAccessor instance. We ‘registered’ the IOrderDataAccessor type with the container to return an instance of the OrderDataAccessor type. So basically, whenever someone asks the container to return an instance of an OrderRepository class, the container knows to instantiate an OrderDataAccessor instance to pass along as the required IOrderDataAccessor object to the OrderRepository constructor.\nAt this point, you may be wondering: “Why go through all this trouble to register the concrete implementation of IOrderDataAccessor to be used in code? We could just as well instantiate the type ourselves!”. That’s certainly true. The code would be slightly uglier, but you’d get the same behavior. Of course, the Windsor container supports XML configuration (either in the app.config or web.config or in a custom configuration file) as well as explicit configuration through code. So you can configure the container through code explicitly, but if there is a config file present, the container will use that configuration instead of the one provided through code. So you could define the defaults in code, and should you need to change it later on, you can just provide a config file.\nYou know what bothers me about our current implementation? We’re still communicating with an OrderRepository instance. If we wanna be really flexible, it would be better if we were communicating with an object that implemented an IOrderRepository interface. So let’s just define the following interface:\npublic interface IOrderRepository\n{\nOrder GetById(Guid id);\nIEnumerable\u0026lt;Order\u0026gt; GetAll();\nOrder FindOne(Criteria criteria);\nIEnumerable\u0026lt;Order\u0026gt; FindMany(Criteria criteria);\nvoid Store(Order order);\n}\nAfter all, that’s all we care about as consumers of a IOrderRepository type. We shouldn’t really care about the concrete implementation. We just need an interface to program to. So let’s change the OrderRepository definition to this:\npublic class OrderRepository : IOrderRepository\nAnd then when we configure our IoC container we do it like this:\nstatic Container()\n{\n_container = new WindsorContainer();\n_container.Register(Component.For\u0026lt;IOrderDataAccessor\u0026gt;).ImplementedBy\u0026lt;OrderDataAccessor\u0026gt;());\n_container.Register(Component.For\u0026lt;IOrderRepository\u0026gt;).ImplementedBy\u0026lt;OrderRepository\u0026gt;());\n}\nNow we can no longer ask the contianer for an OrderRepository interface. But we can ask for an instance that implements the IOrderRepository interface like this:\nIOrderRepository repository = Container.Resolve\u0026lt;IOrderRepository\u0026gt;();\nSo now our client is completely decoupled from the implementation of IOrderRepository, as well as the dependencies it may or may not have.\nOk, lets suppose that this implementation makes it to the production environment. Everything’s working but for some reason, someone makes a decision to retrieve the orders from a specially prepared XML file instead of the database. Unfortunately, your OrderDataAccessor class communicates with a SQL server database. Luckily, the OrderRepository implementation doesn’t know which specific implementation of IOrderDataAccessor it’s using. We just need to make sure that every time someone needs an IOrderRepository instance, it uses the new xml-based IOrderDataAccessor implementation instead of the one we originally intended.\nBecause we’re using Dependency Injection and an IoC container, this only requires changing one line of code:\n_container.Register(Component.For\u0026lt;IOrderDataAccessor\u0026gt;().ImplementedBy\u0026lt;XmlOrderDataAccessor\u0026gt;());\nActually, if we’d put the mapping between the IOrderDataAccessor type and the XmlOrderDataAccessor implementation in an xml file, we wouldn’t even have to change any code! Well, except for the XmlOrderDataAccessor implementation obviously.\nWe can even take this one step further… After the change to the xml-based OrderDataAccessor went successfully, they (the ‘business’) all of a sudden want to log who retrieves or saves each order for auditing purposes.\nWe create an implementation of IOrderRepository which keeps extensive auditing logs so they can be retrieved later on. We could just inherit from the default OrderRepository implementation and add auditing logic before each method is executed. Then we’d only have to configure our IoC container to return a different instance of the IOrderRepository type whenever someone requests it:\nstatic Container()\n{\n_container = new WindsorContainer();\n_container.Register(Component.For\u0026lt;IOrderDataAccessor\u0026gt;().ImplementedBy\u0026lt;XmlOrderDataAccessor\u0026gt;());\n_container.Register(Component.For\u0026lt;IOrderRepository\u0026gt;().ImplementedBy\u0026lt;OrderRepositoryWithAuditing\u0026gt;());\n}\nAgain, our client code does not need to be modified in any way, yet we did modify the runtime behavior of the application. Instead of retrieving the Orders from a SQL database, it’s now retrieving them from an XML file, and the repository is performing auditing as well, without having to change any client code.\nAnd if we were using the xml-configuration features of Windsor, we could get all of this working without even having to recompile the client-assemblies.\nThis was just an introduction to using an IoC contianer (Castle’s Windsor specifically) and we briefly touched on benefits that you can achieve with this way of working. The Windsor container can do much more, but you’ll either have to figure that stuff out yourself, or wait for future posts about its other features/possibilities\nUpdated with new methods and calls for Castle Windsor\n","date":"28 November 2016","externalUrl":null,"permalink":"/introduction-to-ioc-with-windsor/","section":"Articles","summary":"I do love dependency injection, but many developers still seem to miss the point and the reason for having it. If you’re only using it on a small scale, you don’t really need any tools to use the technique. But once you’re used to this design technique, you’ll quickly start using it in many places of your code. If you do, it quickly becomes cumbersome to deal with the real instances of your runtime dependencies manually. This is where tools like Inversion Of Control (IoC) containers come in to play. There are a few solid containers available for the .NET world, and even Microsoft has released their own container. Basically, what the IoC container does for you, is take care of providing dependencies to components in a flexible and customizable way. It allows clients to remain completely oblivious to the dependencies of components they use. This makes it easy to change components without having to modify client code. Not to mention the fact that your components are a lot easier to test, since you can simply inject fake dependencies during your tests.\n","title":"Introduction to IoC with Windsor","type":"articles"},{"content":"","date":"28 November 2016","externalUrl":null,"permalink":"/categories/ios/","section":"Categories","summary":"","title":"IOS","type":"categories"},{"content":"","date":"10 November 2016","externalUrl":null,"permalink":"/categories/extensions/","section":"Categories","summary":"","title":"Extensions","type":"categories"},{"content":"Here is a nice little extension that will take an object and convert it into a CSV file.\nAlso has the option if you want to include a header on the CSV file.\npublic static class ObjectToCsv { public static string ToCsv\u0026lt;T\u0026gt;(this IEnumerable\u0026lt;T\u0026gt; items, bool includeHeading = true) where T : class { var csvBuilder = new StringBuilder(); var properties = typeof(T).GetProperties(); if (includeHeading) { csvBuilder.AppendLine(string.Join(\u0026quot;,\u0026quot;, properties.Select(p =\u0026gt; p.Name.ToCsvValue()).ToArray())); }\nforeach (var item in items) { var line = string.Join(\u0026quot;,\u0026quot;, properties.Select(p =\u0026gt; p.GetValue(item, null).ToCsvValue()).ToArray()); csvBuilder.AppendLine(line); } return csvBuilder.ToString(); }\nprivate static string ToCsvValue\u0026lt;T\u0026gt;(this T item) { if (item == null) return \u0026ldquo;\u0026quot;\u0026quot;\u0026rdquo;;\nif (item is string) { return $\u0026quot;\u0026quot;{item.ToString().Replace(\u0026quot;\u0026quot;\u0026quot;, \u0026ldquo;\\\u0026quot;\u0026rdquo;)}\u0026quot;\u0026quot;; } double dummy; return double.TryParse(item.ToString(), out dummy) ? $\u0026quot;{item}\u0026quot; : $\u0026quot;\u0026quot;{item}\u0026quot;\u0026quot;; } }\n","date":"10 November 2016","externalUrl":null,"permalink":"/object-to-csv-extension/","section":"Articles","summary":"Here is a nice little extension that will take an object and convert it into a CSV file.\nAlso has the option if you want to include a header on the CSV file.\npublic static class ObjectToCsv { public static string ToCsv\u003cT\u003e(this IEnumerable\u003cT\u003e items, bool includeHeading = true) where T : class { var csvBuilder = new StringBuilder(); var properties = typeof(T).GetProperties(); if (includeHeading) { csvBuilder.AppendLine(string.Join(\",\", properties.Select(p =\u003e p.Name.ToCsvValue()).ToArray())); }\nforeach (var item in items) { var line = string.Join(\",\", properties.Select(p =\u003e p.GetValue(item, null).ToCsvValue()).ToArray()); csvBuilder.AppendLine(line); } return csvBuilder.ToString(); }\nprivate static string ToCsvValue\u003cT\u003e(this T item) { if (item == null) return “\"\"”;\nif (item is string) { return $\"\"{item.ToString().Replace(\"\"\", “\\\"”)}\"\"; } double dummy; return double.TryParse(item.ToString(), out dummy) ? $\"{item}\" : $\"\"{item}\"\"; } }","title":"Object to CSV extension","type":"articles"},{"content":"Every vibrant technology marketplace needs an unbiased source of information on best practices as well as an active body advocating open standards. In the Application Security space, one of those groups is the Open Web Application Security Project (or OWASP for short).\nThe Open Web Application Security Project (OWASP) is a 501(c)(3) worldwide not-for-profit charitable organization focused on improving the security of software. Our mission is to make software security visible, so that individuals and organizations are able to make informed decisions. OWASP is in a unique position to provide impartial, practical information about AppSec to individuals, corporations, universities, government agencies and other organizations worldwide. Operating as a community of like-minded professionals, OWASP issues software tools and knowledge-based documentation on application security.\nThe entire Open Web Application Security Project (OWASP) Testing Guide v3 can be downloaded here\n","date":"2 November 2016","externalUrl":null,"permalink":"/owasp-testing-guide-v3/","section":"Articles","summary":"Every vibrant technology marketplace needs an unbiased source of information on best practices as well as an active body advocating open standards. In the Application Security space, one of those groups is the Open Web Application Security Project (or OWASP for short).\n","title":"OWASP Testing Guide v3","type":"articles"},{"content":"Brief Summary Most web applications allow users to reset their password if they have forgotten it, usually by sending them a password reset email and/or by asking them to answer one or more “security questions.” In this test, we check that this function is properly implemented and that it does not introduce any flaw in the authentication scheme. We also check whether the application allows the user to store the password in the browser (“remember password” function).\nDescription of the Issue A great majority of web applications provide a way for users to recover (or reset) their password in case they have forgotten it. The exact procedure varies heavily among different applications, also depending on the required level of security, but the approach is always to use an alternate way of verifying the identity of the user. One of the simplest (and most common) approaches is to have on file the user’s email address (e.g., this is obtained when the user first registers), and send the old password (or a new one) to that address. This scheme is based on the assumption that the user’s email has not been compromised and that is secure enough for this goal.\nAlternatively (or in addition to that), the application could ask the user to answer one or more “secret questions”, which are usually chosen by the user among a set of possible ones. The security of this scheme lies in the ability to provide a way for someone to identify themselves to the system with answers to questions that are not easily answerable via personal information lookups. As an example, a very insecure question would be “your mother’s maiden name” since that is a piece of information that an attacker could find out without much effort. An example of a better question would be “favorite grade-school teacher” since this would be a much more difficult topic to research about a person whose identity may otherwise already be stolen.\nAnother common feature that applications use to provide users a convenience is to cache the password locally in the browser (on the client machine) and having it ‘pre-typed’ in all subsequent accesses. While this feature can be perceived as extremely friendly for the average user, at the same time, it introduces a flaw, as the user account becomes easily accessible to anyone that uses the same account on the client machine.\nBlack Box Testing and Examples Password Reset\nThe first step is to check whether secret questions are used. Sending the password (or a password reset link) to the user email address without first asking for a secret question means relying 100% on the security of that email address, which is not suitable if the application needs a high level of security.\nOn the other hand, if secret questions are used, the next step is to assess their strength.\nAs a first point, how many questions need to be answered before the password can be reset? The majority of applications only need the user to answer to one question, but some critical applications require the user to answer correctly to two or even more questions.\nAs a second step, we need to analyze the questions themselves. Often a self-reset system offers the choice of multiple questions; this is a good sign for the would-be attacker as this presents him/her with options. Ask yourself whether you could obtain answers to any or all of these questions via a simple Google search on the Internet or with a social engineering attack. As a penetration tester, here is a step-by-step walk-through of assessing a password self-reset tool:\nAre there multiple questions offered? If so, try to pick a question which would have a “public” answer; for example, something Google would find with a simple query Always pick questions which have a factual answer such as a “first school” or other facts which can be looked up Look for questions which have few possible options, such as “what make was your first car”. These questions would present the attacker with a short-list of answers to guess at and based on statistics the attacker could rank answers from most to least likely Determine how many guesses you have (if possible) Does the password reset allow unlimited attempts? Is there a lockout period after X incorrect answers? Keep in mind that a lockout system can be a security problem in itself, as it can be exploited by an attacker to launch a Denial of Service against legitimate users Pick the appropriate question based on analysis from above point, and do research to determine the most likely answers How does the password-reset tool (once a successful answer to a question is found) behave? Does it allow immediate change of the password? Does it display the old password? Does it email the password to some pre-defined email address? The most insecure scenario here is if the password reset tool shows you the password; this gives the attacker the ability to log into the account, and unless the application provides information about the last login the victim would not know that his/her account has been compromised. A less insecure scenario is if the password reset tool forces the user to immediately change his/her password. While not as stealthy as the first case, it allows the attacker to gain access and locks the real user out. The best security is achieved if the password reset is done via an email to the address the user initially registered with, or some other email address; this forces the attacker to not only guess at which email account the password reset was sent to (unless the application tells that) but also to compromise that account in order to take control of the victim’s access to the application. The key to successfully exploiting and bypassing a password self-reset is to find a question or set of questions which give the possibility of easily acquiring the answers. Always look for questions which can give you the greatest statistical chance of guessing the correct answer, if you are completely unsure of any of the answers. In the end, a password self-reset tool is only as strong as the weakest question. As a side note, if the application sends/visualizes the old password in cleartext it means that passwords are not stored in a hashed form, which is a security issue in itself.\nPassword Remember\nThe “remember my password” mechanism can be implemented with one of the following methods:\nAllowing the “cache password” feature in web browsers. As of 2014 this is the preferred method as all major browsers have disabled the setting of autocomplete=”off” by default for password fields. Storing the password in a permanent cookie. The password must be hashed/encrypted and not sent in the clear. To check the second implementation type, examine the cookies stored by the application. Verify that the credentials are not stored in cleartext, but are hashed. Examine the hashing mechanism: if it is a common, well-known algorithm, check for its strength; in homegrown hash functions, attempt several usernames to check whether the hash function is easily guessable. Additionally, verify that the credentials are only sent during the login phase, and not sent together with every request to the application.\nGray Box Testing and Examples This test uses only functional features of the application and HTML code that is always available to the client, the graybox testing follows the same guidelines of the previous section. The only exception is for the password encoded in the cookie, where the same gray box analysis described in the Testing for Session Management Schema chapter can be applied.\nOriginal Article\n","date":"2 November 2016","externalUrl":null,"permalink":"/testing-for-vulnerable-remember-password-and-pwd-reset/","section":"Articles","summary":"Brief Summary Most web applications allow users to reset their password if they have forgotten it, usually by sending them a password reset email and/or by asking them to answer one or more “security questions.” In this test, we check that this function is properly implemented and that it does not introduce any flaw in the authentication scheme. We also check whether the application allows the user to store the password in the browser (“remember password” function).\n","title":"Testing for Vulnerable Remember Password and Password Reset","type":"articles"},{"content":"It is important that when working with customers that the architecture is defined and clear in everyone’s mind, I have created this diagram to show the various different areas of the architecture.\nasp-net-web-api-architecture\n","date":"17 October 2016","externalUrl":null,"permalink":"/asp-net-web-api-architecture/","section":"Articles","summary":"It is important that when working with customers that the architecture is defined and clear in everyone’s mind, I have created this diagram to show the various different areas of the architecture.\n","title":"ASP.NET Web API Architecture","type":"articles"},{"content":" Table of Contents Introduction The Workflow Development Environment Staging Environment Production Environment Permissions Conclusion Introduction This guide is aimed to help you better understand how to deal with deployments in your development workflow and provide some best practices. Sometimes a bad production deployment can ruin all the effort you have invested in a development process. Having a solid deployment workflow can become one of the greatest advantages of your team.\nBefore you start, I recommend reading our Developing and Deploying with Branches guide first to get a general idea of how branches should be setup in your repository to be able to fully utilize tips from this guide. It’s a great read!\nNote on Development Branch In this guide you will see a lot of references to a branch called development. In your repository you can use master (Git), trunk (Subversion) or default (Mercurial) for the same purpose, there’s no need to create a branch specifically called “development”. I chose this name because it’s universal for all version control systems.\nThe Workflow Deployments should be treated as part of a development workflow, not as an afterthought. If you are developing a web site or an application, your workflow will usually include at least three environments: Development, Staging and Production. In that case the workflow might look like this:\nDevelopers work on bugs and features in separate branches. Really minor updates can be committed directly to the stable development branch. Once features are implemented, they are merged into the staging branch and deployed to the Staging environment for quality assurance and testing. Once testing is complete, feature branches are merged into the development branch. On the release date, the development branch is merged into production and then deployed to the Production environment. Let’s take a closer look at each environment to see what are the most efficient way to deploy each one of them.\nDevelopment Environment If you make web applications, you don’t need a remote development environment, every developer should have their own local setup.\nMany customers have Development environments set up with automatic deployments on every commit or push. While this gives developers a small advantage of not installing the site or the application on their computers to perform testing locally, it also wastes a lot of time. Every tiny change must be committed, pushed, deployed, and only then it can be verified. If the change was made by mistake, a developer will have to revert it, push it, then redeploy.\nTesting on a local computer removes the need to commit, push and deploy completely. Every change can be verified locally first, then, once it’s more or less stable, it can be pushed to a Staging environment for proper quality assurance testing.\nHowever, what this does provide, is an environment that can ensure the auto-deployment to environment is successful and runs in an independent installation process far removed from the developers’ environment.\nWe do not recommend using deployments for rapidly changing development environments. Running your software locally is the best choice for that sort of testing.\nWe recommend to deploy to the development environment automatically on every commit or push. This will ensure that the build process is full working.\nStaging Environment Once the features are implemented and considered fairly stable, they get merged into the staging branch and then automatically deployed to the Staging environment. This is when quality assurance kicks in: testers go to staging servers and verify that the code works as intended.\nIt is very handy to have a separate branch called staging to represent your staging environment. It will allow developers to deploy multiple branches to the same server simultaneously, simply by merging everything that needs to be deployed to the staging branch. It will also help testers understand what exactly is on staging servers at the moment, just by looking inside the staging branch.\nWe recommend always deploying major releases to staging at a scheduled time, of which the whole team is aware of.\nProduction Environment Once the feature is implemented and tested, it can be deployed to production. If the feature was implemented in a separate branch, it should be merged into a stable development branch first. The branches should be deleted after they are merged to avoid confusion between team members.\nThe next step is to make a to show the difference between the production and development branches to take a quick look at the code that will be deployed to production. This gives you one last chance to spot something that’s not ready or not intended for production. Things like debugger breakpoints, verbose logging or incomplete features.\nOnce the diff review is finished, you can merge the development branch into production and then initialize a deployment of the production branch to your production environment by hand. Specify a meaningful message for your deployment so that your team knows exactly what you deployed.\nMake sure to only merge development branch into production when you actually plan to deploy. Don’t merge anything into production in advance. Merging on time will make files in your production branch match files on your actual production servers and will help everyone better understand the state of your production environment.\nWe recommend always deploying major releases to production at a scheduled time, this should be a MANUALLY process not automated (This can be as simple as clicking a link to start the process going or moving some files, it just needs to be a human who activates the process), of which the whole team is aware of. Find the time when your application is least active and use that time to roll out updates. This may sound obvious, but make sure that it’s not too late in the day, because someone needs to be around after the deployment for at least a few hours to monitor the application and make sure the deployment went fine. Urgent production fixes can be deployed at any time.\nAfter deployment finishes make sure to verify it. It is best to check all the features or fixes that you deployed to make sure they work properly in production. It is a big win if your deployment tool can send an email to all team members with a summary of changes after every deployment. This helps team members to understand what exactly went live and how to communicate it to customers. Beanstalk does this for you automatically.\nYour deployment to production is now complete, time to pop champagne and celebrate with your team!\nRolling Back Sometimes deployments don’t go as planned and things break. In that case you have the possibility to rollback. However, you should be as careful with rollbacks as with production deployments themselves. Sometimes a rollback brings more havoc than the issue it was trying to fix. So first of all stay calm and don’t make any sudden moves. Before performing a rollback, answer the following questions:\nDid it break because of the code that I deployed, or did something else break? You can only rollback files that you deployed, so if the source of the issues is something else a rollback won’t be much help.\nIs it possible to rollback this release? Not all releases can be rolled back. Sometimes a release introduces a new database structure that is incompatible with the previous release. In that case if your rollback, your application will break.\nIf the answer to both questions is “yes”, you can rollback safely. After rollback is done, make sure to fix the bug that you discovered and commit it to either the development branch (if it was minor) or a separate bug-fix branch. Then proceed with the regular bug-fix branch → staging; bug-fix → development → production integration workflow.\nDeploying Urgent Fixes Sometimes you need to deploy a bug-fix to production quickly, when your development branch is not ready for release yet. The workflow in that case stays the same as described above, but instead of merging the development branch into production you actually merge your bug-fix branch first into the development branch, then separately into production, without merging development into production. Then deploy the production branch as usual. This will ensure that only your bug-fix will be deployed to the production environment without all the other stuff from the development branch that’s not ready yet.\nIt is important to merge the bug-fix branch to both the development and production branches in this case, because your production branch should never include anything that doesn’t exist in your stable development branch. The development branch is where developers work all day, so if your fix is only in the production branch they will never see it and it can cause confusion.\nAutomatic Deployments to Production? I can’t stress enough how important it is for all production deployments to be performed and verified by a responsible human being. Using automatic deployments for Production environment is dangerous and can lead to unexpected results. If every commit is deployed to your production site automatically, imagine what happens when someone commits something by mistake or commits an incomplete feature in the middle of the night when the rest of the team is sleeping? Using automatic deployments makes your Production environment very vulnerable. Please don’t do that, always deploy to production manually.\nPermissions Every developer should be able to deploy to the Staging environment. They just need to make sure they don’t overwrite each other’s changes when they do. That’s exactly why the staging branch is a great help: all changes from all developers are getting merged into it so it contains all of them.\nYour Production environment, ideally, should only be accessible to a limited number of experienced developers. These guys should always be prepared to fix the servers immediately after a deployment went rogue.\nConclusion We’ve been using this workflow with many customers for many years to deploy their application. Some of these things were learned the hard way, through broken production servers. Following these guidelines and all production deployments will become incredibly smooth and won’t cause any stress at all.\nOrginal Article\n","date":"13 October 2016","externalUrl":null,"permalink":"/deployments-best-practices/","section":"Articles","summary":" Table of Contents Introduction The Workflow Development Environment Staging Environment Production Environment Permissions Conclusion Introduction This guide is aimed to help you better understand how to deal with deployments in your development workflow and provide some best practices. Sometimes a bad production deployment can ruin all the effort you have invested in a development process. Having a solid deployment workflow can become one of the greatest advantages of your team.\nBefore you start, I recommend reading our Developing and Deploying with Branches guide first to get a general idea of how branches should be setup in your repository to be able to fully utilize tips from this guide. It’s a great read!\nNote on Development Branch In this guide you will see a lot of references to a branch called development. In your repository you can use master (Git), trunk (Subversion) or default (Mercurial) for the same purpose, there’s no need to create a branch specifically called “development”. I chose this name because it’s universal for all version control systems.\nThe Workflow Deployments should be treated as part of a development workflow, not as an afterthought. If you are developing a web site or an application, your workflow will usually include at least three environments: Development, Staging and Production. In that case the workflow might look like this:\nDevelopers work on bugs and features in separate branches. Really minor updates can be committed directly to the stable development branch. Once features are implemented, they are merged into the staging branch and deployed to the Staging environment for quality assurance and testing. Once testing is complete, feature branches are merged into the development branch. On the release date, the development branch is merged into production and then deployed to the Production environment. Let’s take a closer look at each environment to see what are the most efficient way to deploy each one of them.\nDevelopment Environment If you make web applications, you don’t need a remote development environment, every developer should have their own local setup.\nMany customers have Development environments set up with automatic deployments on every commit or push. While this gives developers a small advantage of not installing the site or the application on their computers to perform testing locally, it also wastes a lot of time. Every tiny change must be committed, pushed, deployed, and only then it can be verified. If the change was made by mistake, a developer will have to revert it, push it, then redeploy.\nTesting on a local computer removes the need to commit, push and deploy completely. Every change can be verified locally first, then, once it’s more or less stable, it can be pushed to a Staging environment for proper quality assurance testing.\nHowever, what this does provide, is an environment that can ensure the auto-deployment to environment is successful and runs in an independent installation process far removed from the developers’ environment.\nWe do not recommend using deployments for rapidly changing development environments. Running your software locally is the best choice for that sort of testing.\nWe recommend to deploy to the development environment automatically on every commit or push. This will ensure that the build process is full working.\nStaging Environment Once the features are implemented and considered fairly stable, they get merged into the staging branch and then automatically deployed to the Staging environment. This is when quality assurance kicks in: testers go to staging servers and verify that the code works as intended.\nIt is very handy to have a separate branch called staging to represent your staging environment. It will allow developers to deploy multiple branches to the same server simultaneously, simply by merging everything that needs to be deployed to the staging branch. It will also help testers understand what exactly is on staging servers at the moment, just by looking inside the staging branch.\nWe recommend always deploying major releases to staging at a scheduled time, of which the whole team is aware of.\nProduction Environment Once the feature is implemented and tested, it can be deployed to production. If the feature was implemented in a separate branch, it should be merged into a stable development branch first. The branches should be deleted after they are merged to avoid confusion between team members.\nThe next step is to make a to show the difference between the production and development branches to take a quick look at the code that will be deployed to production. This gives you one last chance to spot something that’s not ready or not intended for production. Things like debugger breakpoints, verbose logging or incomplete features.\nOnce the diff review is finished, you can merge the development branch into production and then initialize a deployment of the production branch to your production environment by hand. Specify a meaningful message for your deployment so that your team knows exactly what you deployed.\nMake sure to only merge development branch into production when you actually plan to deploy. Don’t merge anything into production in advance. Merging on time will make files in your production branch match files on your actual production servers and will help everyone better understand the state of your production environment.\nWe recommend always deploying major releases to production at a scheduled time, this should be a MANUALLY process not automated (This can be as simple as clicking a link to start the process going or moving some files, it just needs to be a human who activates the process), of which the whole team is aware of. Find the time when your application is least active and use that time to roll out updates. This may sound obvious, but make sure that it’s not too late in the day, because someone needs to be around after the deployment for at least a few hours to monitor the application and make sure the deployment went fine. Urgent production fixes can be deployed at any time.\nAfter deployment finishes make sure to verify it. It is best to check all the features or fixes that you deployed to make sure they work properly in production. It is a big win if your deployment tool can send an email to all team members with a summary of changes after every deployment. This helps team members to understand what exactly went live and how to communicate it to customers. Beanstalk does this for you automatically.\nYour deployment to production is now complete, time to pop champagne and celebrate with your team!\nRolling Back Sometimes deployments don’t go as planned and things break. In that case you have the possibility to rollback. However, you should be as careful with rollbacks as with production deployments themselves. Sometimes a rollback brings more havoc than the issue it was trying to fix. So first of all stay calm and don’t make any sudden moves. Before performing a rollback, answer the following questions:\nDid it break because of the code that I deployed, or did something else break? You can only rollback files that you deployed, so if the source of the issues is something else a rollback won’t be much help.\nIs it possible to rollback this release? Not all releases can be rolled back. Sometimes a release introduces a new database structure that is incompatible with the previous release. In that case if your rollback, your application will break.\nIf the answer to both questions is “yes”, you can rollback safely. After rollback is done, make sure to fix the bug that you discovered and commit it to either the development branch (if it was minor) or a separate bug-fix branch. Then proceed with the regular bug-fix branch → staging; bug-fix → development → production integration workflow.\nDeploying Urgent Fixes Sometimes you need to deploy a bug-fix to production quickly, when your development branch is not ready for release yet. The workflow in that case stays the same as described above, but instead of merging the development branch into production you actually merge your bug-fix branch first into the development branch, then separately into production, without merging development into production. Then deploy the production branch as usual. This will ensure that only your bug-fix will be deployed to the production environment without all the other stuff from the development branch that’s not ready yet.\nIt is important to merge the bug-fix branch to both the development and production branches in this case, because your production branch should never include anything that doesn’t exist in your stable development branch. The development branch is where developers work all day, so if your fix is only in the production branch they will never see it and it can cause confusion.\nAutomatic Deployments to Production? I can’t stress enough how important it is for all production deployments to be performed and verified by a responsible human being. Using automatic deployments for Production environment is dangerous and can lead to unexpected results. If every commit is deployed to your production site automatically, imagine what happens when someone commits something by mistake or commits an incomplete feature in the middle of the night when the rest of the team is sleeping? Using automatic deployments makes your Production environment very vulnerable. Please don’t do that, always deploy to production manually.\nPermissions Every developer should be able to deploy to the Staging environment. They just need to make sure they don’t overwrite each other’s changes when they do. That’s exactly why the staging branch is a great help: all changes from all developers are getting merged into it so it contains all of them.\nYour Production environment, ideally, should only be accessible to a limited number of experienced developers. These guys should always be prepared to fix the servers immediately after a deployment went rogue.\nConclusion We’ve been using this workflow with many customers for many years to deploy their application. Some of these things were learned the hard way, through broken production servers. Following these guidelines and all production deployments will become incredibly smooth and won’t cause any stress at all.\nOrginal Article\n","title":"Deployments Best Practices","type":"articles"},{"content":"","date":"13 October 2016","externalUrl":null,"permalink":"/categories/team-services/","section":"Categories","summary":"","title":"Team Services","type":"categories"},{"content":"","date":"13 October 2016","externalUrl":null,"permalink":"/categories/auto-deployment/","section":"Categories","summary":"","title":"Auto Deployment","type":"categories"},{"content":" Table of Contents Introduction Coding in master/trunk “branches” Branching Workflow Further Reading: Branching with Beanstalk Introduction Getting started with Version Control can be an eye-opening experience. You may have already said to yourself, “How did I work without this?”. Now that you’ve got the basics of Version Control down, you want to start getting really productive by continuing to improve your workflow. Your next step is learning to code in branches.\nCoding in branches is a simple practice that keeps you and your work more organised. Branches let you easily maintain your “in-progress” work separately from your completed, tested, and stable code. Not only is this an effective way to collaborate with others, but it will also allow you to automate the deployment of updates, when needed and fixes to your servers.\nCoding in master/trunk “branches” Even if you don’t know how to use branching in your development process, you’ve already been using a branch just by committing your code to version control. In all major version control systems, each repository contains at least one branch by default, your working branch:\nin Subversion this is a folder called trunk, in Git this is a branch called master. Without configuring anything, your first commit to any repository will be made to this working branch.\nEach version control system has a different approach to creating, merging, and deleting branches. We’ll be focusing on overall development process, and suggest that you refer to the documentation of your preferred VCS for specific details about commands:\nSVN Branching Git Branching Branching Workflow Using branches can seem complicated without some guidance. We’re going to help you by focusing on two specific uses for branches and the benefits of having them in your workflow.\nBenefits of Branches: Building Features \u0026amp; Fixing Bugs Most coding falls into one of these two categories: you’re either building new features or fixing bugs in an existing codebase. A problem occurs when those two things need to be happen at the same time.\nImagine that you’ve recently launched big Feature X. Things are going well at first, so you move on to start the next task on your to-do list, awesome Feature Y. You start coding and committing changes to your repository, but along the way discover a problem with big Feature X that you need to fix right away. What do you do?\nIf all of your work is being done in the default working branch of your repository, you’ll need to figure out how to save the work you’ve done so far on Feature Y, revert your repository to the state it was in when you deployed Feature X, make your fix, and then re-introduce your work from Feature Y. This is messy, and you could potentially lose some of your work or introduce new bugs.\nInstead, you should be doing all of your work in a feature or bug-fix branches and let the VCS do the hard work for you. You would branch your repository from the point where Feature X was deployed, creating an alternate working copy for you to do new work on. Your Feature Y branch includes the entire repository’s history and code, but a separate history “starts” from the moment the branch is created. This allows you to work on the Feature Y branch, committing to your hearts content, without disturbing the code that you deployed to release Feature X.\nOnly once the feature is tested and complete, ready for deployment, you can merge that branch back into your main working branch.\nThis also means you can switch between a feature branch to the default working branch any time to create new branches from that point – like the bug-fix that you need to make. After switching back to the working branch, you would create a bug-fix branch. Working on the bug-fix in its own branch might not seem necessary if the fix is small, but following this practice will help you avoid situations where small bug-fixes turn into bigger bug-fixes, potentially leaving your working branch in a messy state.\nBest Practices with Feature \u0026amp; Bug Branches Try to avoid committing unfinished work to your repository’s default working branch. Create a branch any time you begin non-trivial work including features and complex bug-fixes. Don’t forget to delete feature branches once they were merged into stable branch. This will keep your repository clean. Benefits of Branching: Server Environment Branches Another reason to use version control is so that you can use your repository as the source to deploy code to your servers. Much like feature and bug-fix branches, environment branches make it easy for you to separate your in-progress code from your stable code. Using environment branches and deploying from them means you will always know exactly what code is running on your servers in each of your environments.\nWe’ve been talking about your “default working branch” – but you can also think of this as your development environment branch. It’s a good idea to keep this branch clean – this is easily done by using feature and bug-fix branches and only merging them back to your development branch once they are tested. In other words, at any point in time your development branch should contain only stable code. Therefore, we will be using the name “stable” from now on in this guide to refer to this branch.\nUsing Production and Staging Branches In addition to your development environment, you’re likely to have at least one other environment:production, where your website or application actually runs. Having a production environment branch and making that the only source of code that goes to production ensures that you have a snapshot of what is on your production server at any time, and a granular history of what’s been added to production and when.\nIn most cases you will have a staging environment as well, where your team or clients can review changes together. Having a staging environment branch will help you keep that environment with the same benefits as a production branch.\nDiff Branches for Easy Code Review \u0026amp; Release Notes When your development environment has been updated with features and bug-fixes that are tested, you can use your VCS to do a diff between your stable branch and staging branch to see what would be deployed that’s not currently on staging. This is a great opportunity to look for low quality or incomplete code, debug code, and other development leftovers that shouldn’t be deployed. This diff can also be helpful in writing your release notes.\nNever Merge to Environment Branches Without Deploying In order to keep your environment branches in sync with the environments, it’s a best practice to only execute a merge into an environment branch at the time you intend to deploy. If you complete a merge without deploying, your environment branch will be out of sync with your actual production environment.\nWith environment branches, you never want to commit changes directly to the branch. By only merging code from your stable branch into staging or production branches, you ensure that changes are flowing in one direction: from feature and bug-fix branches to stable and staging environments, and from stable to production. This keeps your history clean, and again, lets you be confident about knowing what code is running in which environments.\nBest Practices with Environment Branches Use your repository’s default working branch as your “stable” branch. Create a branch for each environment, including staging and production. Never merge into an environment branch unless you are ready to deploy to that environment. Perform a diff between branches before merging—this can help prevent merging something that wasn’t intended, and can also help with writing release notes. Merges should only flow in one direction: first from feature to staging for testing; then from feature to stable once tested; then from stable to production to ship. Further Reading: Branching with Beanstalk This is just an overview of some of the most common practices for using branches in version control. If you’re using Beanstalk, we’ve included some resources to help you take advantage of branching.\nBranching and Merging with Cornerstone (SVN) Branching and Merging with Tower (Git) Original Article\n","date":"13 October 2016","externalUrl":null,"permalink":"/developing-and-deploying-with-branches/","section":"Articles","summary":" Table of Contents Introduction Coding in master/trunk “branches” Branching Workflow Further Reading: Branching with Beanstalk Introduction Getting started with Version Control can be an eye-opening experience. You may have already said to yourself, “How did I work without this?”. Now that you’ve got the basics of Version Control down, you want to start getting really productive by continuing to improve your workflow. Your next step is learning to code in branches.\nCoding in branches is a simple practice that keeps you and your work more organised. Branches let you easily maintain your “in-progress” work separately from your completed, tested, and stable code. Not only is this an effective way to collaborate with others, but it will also allow you to automate the deployment of updates, when needed and fixes to your servers.\nCoding in master/trunk “branches” Even if you don’t know how to use branching in your development process, you’ve already been using a branch just by committing your code to version control. In all major version control systems, each repository contains at least one branch by default, your working branch:\nin Subversion this is a folder called trunk, in Git this is a branch called master. Without configuring anything, your first commit to any repository will be made to this working branch.\nEach version control system has a different approach to creating, merging, and deleting branches. We’ll be focusing on overall development process, and suggest that you refer to the documentation of your preferred VCS for specific details about commands:\nSVN Branching Git Branching Branching Workflow Using branches can seem complicated without some guidance. We’re going to help you by focusing on two specific uses for branches and the benefits of having them in your workflow.\nBenefits of Branches: Building Features \u0026 Fixing Bugs Most coding falls into one of these two categories: you’re either building new features or fixing bugs in an existing codebase. A problem occurs when those two things need to be happen at the same time.\nImagine that you’ve recently launched big Feature X. Things are going well at first, so you move on to start the next task on your to-do list, awesome Feature Y. You start coding and committing changes to your repository, but along the way discover a problem with big Feature X that you need to fix right away. What do you do?\nIf all of your work is being done in the default working branch of your repository, you’ll need to figure out how to save the work you’ve done so far on Feature Y, revert your repository to the state it was in when you deployed Feature X, make your fix, and then re-introduce your work from Feature Y. This is messy, and you could potentially lose some of your work or introduce new bugs.\nInstead, you should be doing all of your work in a feature or bug-fix branches and let the VCS do the hard work for you. You would branch your repository from the point where Feature X was deployed, creating an alternate working copy for you to do new work on. Your Feature Y branch includes the entire repository’s history and code, but a separate history “starts” from the moment the branch is created. This allows you to work on the Feature Y branch, committing to your hearts content, without disturbing the code that you deployed to release Feature X.\nOnly once the feature is tested and complete, ready for deployment, you can merge that branch back into your main working branch.\nThis also means you can switch between a feature branch to the default working branch any time to create new branches from that point – like the bug-fix that you need to make. After switching back to the working branch, you would create a bug-fix branch. Working on the bug-fix in its own branch might not seem necessary if the fix is small, but following this practice will help you avoid situations where small bug-fixes turn into bigger bug-fixes, potentially leaving your working branch in a messy state.\nBest Practices with Feature \u0026 Bug Branches Try to avoid committing unfinished work to your repository’s default working branch. Create a branch any time you begin non-trivial work including features and complex bug-fixes. Don’t forget to delete feature branches once they were merged into stable branch. This will keep your repository clean. Benefits of Branching: Server Environment Branches Another reason to use version control is so that you can use your repository as the source to deploy code to your servers. Much like feature and bug-fix branches, environment branches make it easy for you to separate your in-progress code from your stable code. Using environment branches and deploying from them means you will always know exactly what code is running on your servers in each of your environments.\nWe’ve been talking about your “default working branch” – but you can also think of this as your development environment branch. It’s a good idea to keep this branch clean – this is easily done by using feature and bug-fix branches and only merging them back to your development branch once they are tested. In other words, at any point in time your development branch should contain only stable code. Therefore, we will be using the name “stable” from now on in this guide to refer to this branch.\nUsing Production and Staging Branches In addition to your development environment, you’re likely to have at least one other environment:production, where your website or application actually runs. Having a production environment branch and making that the only source of code that goes to production ensures that you have a snapshot of what is on your production server at any time, and a granular history of what’s been added to production and when.\nIn most cases you will have a staging environment as well, where your team or clients can review changes together. Having a staging environment branch will help you keep that environment with the same benefits as a production branch.\nDiff Branches for Easy Code Review \u0026 Release Notes When your development environment has been updated with features and bug-fixes that are tested, you can use your VCS to do a diff between your stable branch and staging branch to see what would be deployed that’s not currently on staging. This is a great opportunity to look for low quality or incomplete code, debug code, and other development leftovers that shouldn’t be deployed. This diff can also be helpful in writing your release notes.\nNever Merge to Environment Branches Without Deploying In order to keep your environment branches in sync with the environments, it’s a best practice to only execute a merge into an environment branch at the time you intend to deploy. If you complete a merge without deploying, your environment branch will be out of sync with your actual production environment.\nWith environment branches, you never want to commit changes directly to the branch. By only merging code from your stable branch into staging or production branches, you ensure that changes are flowing in one direction: from feature and bug-fix branches to stable and staging environments, and from stable to production. This keeps your history clean, and again, lets you be confident about knowing what code is running in which environments.\nBest Practices with Environment Branches Use your repository’s default working branch as your “stable” branch. Create a branch for each environment, including staging and production. Never merge into an environment branch unless you are ready to deploy to that environment. Perform a diff between branches before merging—this can help prevent merging something that wasn’t intended, and can also help with writing release notes. Merges should only flow in one direction: first from feature to staging for testing; then from feature to stable once tested; then from stable to production to ship. Further Reading: Branching with Beanstalk This is just an overview of some of the most common practices for using branches in version control. If you’re using Beanstalk, we’ve included some resources to help you take advantage of branching.\nBranching and Merging with Cornerstone (SVN) Branching and Merging with Tower (Git) Original Article\n","title":"Developing and Deploying with Branches","type":"articles"},{"content":"","date":"13 October 2016","externalUrl":null,"permalink":"/categories/tfs/","section":"Categories","summary":"","title":"TFS","type":"categories"},{"content":"Using Azure can open up a can of worm around security and many customers have many concerns\nMicrosoft do a lot of things to keep your Team Service project safe and secure, refer to this link for details: Visual Studio Team Services Data Protection Overview.\nYou can deploy your own build agent which you can have full control and easy to configure your machines to only accept the deployment from that build agent.\nAnother URL link I found from Microsoft Virtual Learning which might be useful:\nGetting Started with Azure Security for the IT Professional\nDo IT security concerns keep you up at night? You’re not alone! Many IT Pros want to extend their organization’s infrastructure but need reassurance about security. Whether you are researching a hybrid or a public cloud model with Microsoft Azure, the question remains the same: Does the solution meet your own personal and your organization’s bar for security, including industry standards, attestations, and ISO certifications? In this demo-filled course, explore these and other hot topics, as a team of security experts and Azure engineers takes you beyond the basic certifications and explores what’s possible inside Azure. See how to design and use various technologies to ensure that you have the security and architecture you need to successfully launch your projects in the cloud. Dive into datacenter operations, virtual machine (VM) configuration, network architecture, and storage infrastructure. Get the information and the confidence you need, from the pros who know, as they demystify security in the cloud.\nThis article is very useful is you need to deploy from a remote server\nhttp://myalmblog.com/2014/04/configuring-on-premises-build-server-for-visual-studio-online/\n","date":"13 October 2016","externalUrl":null,"permalink":"/visual-studio-team-services-security/","section":"Articles","summary":"Using Azure can open up a can of worm around security and many customers have many concerns\nMicrosoft do a lot of things to keep your Team Service project safe and secure, refer to this link for details: Visual Studio Team Services Data Protection Overview.\n","title":"Visual Studio Team Services Security","type":"articles"},{"content":"It is important that when using Azure that you take security very seriously, I’ve been looking around to see if I can get together as much information as I can to help businesses protect the environments that they relay on so much to run their businesses.\nI found these short introductions to Azure Security Center which are worth looking over:\nIntroduction to Azure Security Center A brief overview of how Azure Security Center helps you protect, detect and respond to cybersecurity threats.\nAzure Security Center Overview With Azure Security Center, you get a central view of the security state of all of your Azure resources. At a glance, verify that the appropriate security controls are in place and configured correctly. Scott talks to Sara Fender who explains it all!\nAzure Security Center – Threat Detection With Azure Security Center, you get a central view of the security state of all of your Azure resources. At a glance, verify that the appropriate security controls are in place and configured correctly. Scott talks to Sarah Fender who explains how Security Center integrates Threat Detection.\nAzure Security Center – Focus on Prevention Staying ahead of current and emerging threats requires an integrated, analytics-driven approach. By combining Microsoft global threat intelligence and expertise with insights into security-related events across your Azure deployments, Security Center helps you detect actual threats early, and it reduces false positives. Scott talks to Sara Fender who breaks down the details.\n","date":"12 October 2016","externalUrl":null,"permalink":"/azure-security-center/","section":"Articles","summary":"It is important that when using Azure that you take security very seriously, I’ve been looking around to see if I can get together as much information as I can to help businesses protect the environments that they relay on so much to run their businesses.\n","title":"Azure Security Center","type":"articles"},{"content":"","date":"30 May 2016","externalUrl":null,"permalink":"/categories/azure-resource-manager/","section":"Categories","summary":"","title":"Azure Resource Manager","type":"categories"},{"content":"Things have moved forward in the Microsoft’s Azure cloud platform since I very first started using Azure. One thing is for sure is that the number of services available has grown and with this growth comes the responsibility of ensuring that you can successfully deploy what you have built with the minimum about of trouble in the quickest possible time. Along came the Azure Resource Manager (ARM) which is the service used to provision resources in your Azure subscription. It was first announced at Build 2014 when the new Azure portal (portal.azure.com) was announced and provides a new set of JSON API’s that are used to provision resources. Before ARM, developers and IT professionals used the Azure Service Management API and the old portal (manage.windowsazure.com) to provision resources. Both portals and sets support the of API’s. However, going forward you should be using ARM, the new API’s, and the new Azure portal to provision and manage your Azure resources.\nAzure Friday has a nice easy overview of the Azure Resource Manager. Scott talks to Mahesh Thiagarajan about the new Azure JSON-based APIs for Azure that now include Compute, Network, and Storage. Orchestrating large system deployments is easier and more declarative than ever.\nThe Benefits of using the Azure Resource Manager There are many benefits of ARM that the first Service Management API’s (and old portal) could not deliver. The advantages that ARM provides can be broken down into a few areas:\nDeclaratively Provision Resources Azure Resouce Management provides us with a way to describe resources in a resource group using JSON documents. There are many resource groups, for example, Web App, Storage Account, SQL Database. In the JSON document, you can describe the properties for each of the resources such as the type of storage account, the size of the SQL Database, and settings for the Web App; there are many more options available. The advantage here is that we can describe the environment we want and send that to Azure Resource Management to make it happen.\nSmarter and Faster Provisioning of Resources Before ARM, you had to provision resources independently to support your application, and it was up to you to figure dependencies between resources and accommodate for these in your deployment scripts.\nARM is also able to determine when it can provision resources simultaneously allow for faster provisioning of all the resources described in the resource group is achieved.\nResource Groups as a Unit of Management Before ARM, the relationship between resources (i.e. a web app and a database) was something you had to manage yourself. Include trying to compute costs across multiple resources to determine the all-up costs for an application. In the ARM era, since the resource group containing the resources for your application are a single unit of deployment, the resource group also becomes a unit of management. By resource grouping it enables you to do things like determining costs for the entire resource group (and all he resources within), making accounting and chargebacks easier to manage.\nBefore ARM, if you wanted to enable a user or group of users to manage the resources for a particular application, then you had to make them a co-administrator on your Azure Subscription. The users have full capability to add, delete, and modify any resource in the subscription, not just the resources for that application. With ARM, you can configure Role-Based Access Control for resources and resource groups, enabling you to assign management permissions to only the resource group for only the users that need access to manage it. When those users sign-in to Azure they will be able to see the resource group you gave them access to but not the rest of the resources in your subscription. You can even assign Role-Based Access Control permissions to individual resources if you needed to.\nIdempotent Provisioning of Resources Post ARM, automating the provisioning of resources meant that you had to account for situations where some, but not all, of your resources, would be successfully provisioned. With ARM, when you send it the JSON document describing your environment, ARM knows which resources already exist and which ones do not and will provision only the resources missing to complete the resource group.\nTools The Azure portal is an excellent way to get started using Azure Resource Manager with nothing more than your browser. When you create resources using the Azure portal (portal.azure.com) you are using ARM. Eventually, you will need to write a deployment template that describes all the resources you want ARM to provision. And to be scalable, you will need to automate the deployment. You could start with something from the Azure Quick start Templates, but at some point, you will likely need (or want) to build your deployment template from scratch. For this, Visual Studio and PowerShell are the two tools are strongly recommended.\nVisual Studio When it is time to write your ARM deployment templates, you will find that Visual Studio and the Azure Tools delivers an incredible experience that includes JSON IntelliSense in the editor and a JSON outline tool to visualise the resources. Writing ARM deployment templates is not a trivial task. By using Visual Studio and the Azure Tools, you will be able to create deployment templates from scratch in a matter of minutes.\nA version of the Azure Tools SDK is available for VS 2015. The Azure Tools provides an Azure Resource Group project template to get you started as shown below. In subsequent posts, I’ll be demonstrating how to use this project template.\nPowershell The project template mentioned in the previous section generates a PowerShell deployment script that can be used to send your deployment to ARM in an automated manner. The script uses the latest Azure “RM” Cmdlets that you can download and install from here. Most of the code in the deployment script handles uploading artefacts that ARM may need to deploy your environment. For example, if your deployment template describes a virtual machine that requires a DSC extension to add additional configuration to the VM after Azure has created it, then the DSC package (zip file) would need to be generated and uploaded to a storage account for ARM to use while it is provisioning the VM. But, if you scroll down past all that to the bottom of the script file you will see two commands in the script (shown below).\nThe first command, New-AzureRmResourceGroup, only creates the resource group using a resource group name that you provide.\nThe second command, New-AzureRmResourceGroupDeployment, pushes your deployment template and parameters for the deployment template to ARM. After ARM receives the files, it starts provisioning the resources described in your deployment template.\nA workflow diagram of how these tools are used to deploy an environment using Azure Resource Manager is shown here.\nSummary\nIn this post, We’ve introduced Azure Resource Manager and highlighted some significant advantages it brings to the platform. Concluded by adding a couple of tools you should consider using to author your deployment templates.\nOriginal post by Rick Rainey\n","date":"30 May 2016","externalUrl":null,"permalink":"/azure-resource-manager-compute-templates/","section":"Articles","summary":"Things have moved forward in the Microsoft’s Azure cloud platform since I very first started using Azure. One thing is for sure is that the number of services available has grown and with this growth comes the responsibility of ensuring that you can successfully deploy what you have built with the minimum about of trouble in the quickest possible time. Along came the Azure Resource Manager (ARM) which is the service used to provision resources in your Azure subscription. It was first announced at Build 2014 when the new Azure portal (portal.azure.com) was announced and provides a new set of JSON API’s that are used to provision resources. Before ARM, developers and IT professionals used the Azure Service Management API and the old portal (manage.windowsazure.com) to provision resources. Both portals and sets support the of API’s. However, going forward you should be using ARM, the new API’s, and the new Azure portal to provision and manage your Azure resources.\n","title":"Azure Resource Manager Compute Templates","type":"articles"},{"content":"Have you ever updated to the newest version of WordPress, and then noticed that your site starts to have a bunch of problems? Don’t freak out. A lot of the times, it’s an issue with a plugin or theme that’s not compatible with the newest update. Sometimes (rarely) there’s an issue with the WordPress update itself. Whatever the case, one of of the quickest solutions to bring your site back to normal is to downgrade WordPress back to the previous version.\nCompatibility issues are one of the reasons I try to avoid plugins and themes that don’t get updated regularly. I don’t want to be stuck with an older version of WordPress just because one of my plugins or themes doesn’t work with the latest update. Before you go through the process of downgrading, I’d suggest checking to see if a plugin is what’s causing the issue. If it is, you can just disable the plugin until there’s an update for it. If it’s a problem with the theme though, that’s an entirely different story. That’s when you’ll want to consider downgrading your version of WordPress.\nBefore you downgrade, I’d highly recommend making sure you have a backup of your site just in case things don’t go as planned and everything gets screwed up. I’ve never run into an issue but I always have the feeling that the one time I downgrade and my site goes berserk, I won’t have a backup. There are tons of backup plugins for WordPress and your web host might/should be able to provide you with the latest backup they have.\nThe first thing you’re going to need is a previous WordPress release. You can download any of the previous WordPress versions here –\u0026gt; backup plugins for WordPress. Only downgrade down to the version before the newest one. Don’t go way back into the archives to version 1.1. Some of the older versions of WordPress have security issues that could put your site at risk.\nHere’s how to downgrade WordPress to an older version.\nMANUAL WORDPRESS DOWNGRADE TUTORIAL STEP 1: DEACTIVATE ALL YOUR PLUGINS After you’ve created a backup of your site and downloaded the WordPress version you want to downgrade to, it’s time to actually downgrade. The first thing you want to do is login to your WP Dashboard and deactivate all of your plugins.\nSTEP 2: LOGOUT OF WORDPRESS After all your plugins have been deactivated, logout of WordPress.\nSTEP 3: USE AN FTP CLIENT AND LOCATE YOUR SITE’S WORDPRESS FILES This step will require that you have an FTP client. An FTP client allows you to access all of the files on your site. I use FireFTP from Firefox and FileZilla is another very popular option. Both are free and you can’t go wrong with either. The images in this tutorial are from FireFTP. In your FTP client, locate your WordPress files (wp-admin, wp-content, etc.). In FireFTP, they will be the first thing you see when you open your site’s folder.\nSTEP 4: DELETE THE WP-ADMIN AND WP-INCLUDES FOLDERS Delete both the wp-admin and wp-includes folders. Do not touch the wp-content folder! You can leave all of the other files alone because you will overwrite them in the next step.\nSTEP 5: TRANSFER THE FILES FROM THE PREVIOUS WP VERSION TO YOUR SITE WITH FTP While you’re still in your FTP client, go into the folder where you have the WordPress version you want to downgrade to. Transfer over everything except the wp-content folder. After all the files have been transferred, your downgrade is finished.\nSTEP 6: UPDATE YOUR WORDPRESS DATABASE Login to your WP Dashboard. You will be prompted to update your WordPress database. Click on “Update WordPress Database” and then click continue to login.\nOnce you’re logged in, you should see that you’re running whatever version of WordPress that you downgraded to. Congrats!\nA word of caution. I don’t recommend using older versions of WordPress when newer ones are available. Like I said in the beginning, a lot of the updates come with security patches to stop known security threats that could leave your site open to hackers.\nIf your theme isn’t compatible with the most current version of WordPress, contact the theme developer and let them know. If there’s no support offered for your theme, then you’ll want to switch to a different one that’s updated on a regular basis.\nOriginal article can be found here\n","date":"15 April 2016","externalUrl":null,"permalink":"/downgrading-wordpress/","section":"Articles","summary":"Have you ever updated to the newest version of WordPress, and then noticed that your site starts to have a bunch of problems? Don’t freak out. A lot of the times, it’s an issue with a plugin or theme that’s not compatible with the newest update. Sometimes (rarely) there’s an issue with the WordPress update itself. Whatever the case, one of of the quickest solutions to bring your site back to normal is to downgrade WordPress back to the previous version.\n","title":"Downgrading WordPress","type":"articles"},{"content":"","date":"15 April 2016","externalUrl":null,"permalink":"/categories/wordpress/","section":"Categories","summary":"","title":"WordPress","type":"categories"},{"content":"","date":"15 April 2016","externalUrl":null,"permalink":"/categories/woocommerce/","section":"Categories","summary":"","title":"WooCommerce","type":"categories"},{"content":"The first four shortcodes are used for special WooCommerce pages and are sometimes automatically inserted into the pages by WooCommerce during installation. They should not otherwise be used. All others can be used throughout and can be used more than once.\nShortcodes for WooCommerce sites only\nShortcode\nParameter\nMeaning\nwoocommerce_cart\nnone\nShows the content of the cart page.\nwoocommerce_checkout\nnone\nShows the content of the checkout page.\nwoocommerce_order_tracking\nnone\nShows the user a form with which he can enquire about the status of his orders.\nwoocommerce_my_account\ncurrent_user, order_count\nShows the content of the user account page.\nNon-specific WooCommerce shortcodes\nShortcode\nParameter\nMeaning\nrecent_products\nper_page, columns, orderby, order\nShows new products.\nfeatured_products\nper_page, columns, orderby, order\nShows featured products.\nproduct\nid or sku\nShows a single product.\nproducts\nids or skus, columns, orderby, order\nShows several predetermined products.\nadd_to_cart\nid or sku, style\nShows the price and the “add to cart” button of a single product.\nadd_to_cart_url\nid or sku\nDisplays the URL of the “add to cart” button of a particular product in text form.\nproduct_page\nid or sku\nShows the detail page of a product.\nproduct_category\nper_page, columns, orderby, order, category\nShows the products in a category.\nproduct_categories\nnumber, orderby, order, columns, hide_empty, parent, ids\nShows existing product categories.\nsale_products\nper_page, columns, orderby, order\nShows products on offer.\nbest_selling_products\nper_page, columns\nShows best-selling products.\ntop_rated_products\nper_page, columns, orderby, order\nShows top-rated products.\nproduct_attribute\nper_page, columns, orderby, order, attribute, filter\nShows products with a particular attribute.\nrelated_products\nper_page, columns, orderby\nShows related products.\nNote: The parameters orderby and order are WordPress-specific and are described in more detail in the Codex.\n[woocommerce_cart]\nShows the content of the cart page and everything that comes with it; list of products in the basket, voucher entry, shopping cart total, Proceed to checkout button, product recommendation etc. This shortcode will be automatically inserted into the cart page when installing WooCommerce.\nParameter\nnone Example\nCrayon Syntax Highlighter v2.7.1\n[woocommerce_cart]\n1\n[woocommerce_cart]\n[Format Time: 0.0006 seconds]\n[woocommerce_checkout]\nShows the content of the checkout page and everything that comes with it; invoice details, order overview Continue button etc. This shortcode will be automatically inserted into the checkout page when installing WooCommerce.\nParameter\nnone Example\nCrayon Syntax Highlighter v2.7.1\n[woocommerce_checkout]\n1\n[woocommerce_checkout]\n[Format Time: 0.0004 seconds]\n[woocommerce_order_tracking]\nShows the user a form with which he can enquire about the status of his orders by stating the order number and email address. After entering the data, the customer is redirected to a page that displays the status and a summary of the order.\nParameter\nnone Example\nCrayon Syntax Highlighter v2.7.1\n[woocommerce_order_tracking]\n1\n[woocommerce_order_tracking]\n[Format Time: 0.0004 seconds]\n[woocommerce_my_account]\nShows the content of the My Account page and everything that comes with it; overview of past orders, billing address and delivery address etc. The customer can also edit his data here. This shortcode will be automatically inserted into the My Account page when installing WooCommerce.\nParameter\ncurrent_user default: ” The customer whose My Account page is to be displayed. This is determined automatically using the function get_user_by get_user_by( ‘id’, get_current_user_id() ) order_count default: 15 Number of orders to be displayed, -1 for the display of all orders. Example\nCrayon Syntax Highlighter v2.7.1\n[woocommerce_my_account order_count=”12″]\n1\n[woocommerce_my_account order_count=“12”]\n[Format Time: 0.0005 seconds]\n[recent_products]\nShows recently added products, sorted according to various criteria. For presentation purposes you can specify the number of products to be displayed per page and the number of columns.\nParameter\nper_page default: 12 Number of products displayed per page. columns default: 4 Number of columns. orderby default: date Sort key. order default: desc Sort order. Example\nCrayon Syntax Highlighter v2.7.1\n[recent_products per_page=”12″ columns=”4″]\n1\n[recent_products per_page=“12” columns=“4”]\n[Format Time: 0.0006 seconds]\n[featured_products]\nShows featured products, sorted according to various criteria. For presentation purposes you can specify the number of products to be displayed per page and the number of columns. Comparable to recent_products.\nParameter\nper_page default: 12 Number of products displayed per page. columns default: 4 Number of columns. orderby default: date Sort key. order default: desc Sort order. Example\nCrayon Syntax Highlighter v2.7.1\n[featured_products per_page=”12″ columns=”4″]\n1\n[featured_products per_page=“12” columns=“4”]\n[product]\nShows a single product that is specified by the ID or the item number (SKU). Make sure the catalog visibility is not set to hidden or the product will not be shown. The ID of a product can be determined in the dashboard on the product page. It will be displayed when you hover the mouse over the product in the name column. You can find the item number in the Art.-Nr. column.\nParameter\nid default: ” Product ID sku default: ” Product item number Examples\nCrayon Syntax Highlighter v2.7.1\n[product id=”99″]\n1\n[product id=“99”]\nCrayon Syntax Highlighter v2.7.1\n[product sku=”ART103″]\n1\n[product sku=“ART103”]\n[products]\nDisplays several products, which are specified by their IDs or by their item number (SKU). Make sure the catalog visibility is not set to hidden or the product will not be shown. Comparable to product.\nParameter\nid default: ” Product ID sku default: ” Product item number columns default: 4 Number of columns. orderby default: title Sort key. order default: asc Sort order. Examples\nCrayon Syntax Highlighter v2.7.1\n[products ids=”1, 2, 3, 4, 5″]\n1\n[products ids=“1, 2, 3, 4, 5”]\nCrayon Syntax Highlighter v2.7.1\n[products skus=”ART12, ART22, ART50″ orderby=”date” order=”desc”]\n1\n[products skus=“ART12, ART22, ART50” orderby=“date” order=“desc”]\n[add_to_cart]\nShows the price and the Add to Cart button of a product, which is specified by the ID or the item number (SKU). The style parameter can be used for formatting.\nParameter\nid default: ” Product ID sku default: ” Product item number style default: border:4px solid #ccc; padding: 12px; Formatting Example\nCrayon Syntax Highlighter v2.7.1\n[add_to_cart id=”99″]\n1\n[add_to_cart id=“99”]\n[add_to_cart_url]\nDisplays the URL of the add to cart button of a particular product in text form. The product is specified by the ID or the item number (SKU).\nParameter\nid default: ” Product ID sku default: ” Product item number Example\nCrayon Syntax Highlighter v2.7.1\n[add_to_cart_url id=”99″]\n1\n[add_to_cart_url id=“99”]\n[product_page]\nShows the detail page of a product which is specified by the ID or the item number.\nParameter\nid default: ” Product ID sku default: ” Product item number Examples\nCrayon Syntax Highlighter v2.7.1\n[product_page id=”99″]\n1\n[product_page id=“99”]\nCrayon Syntax Highlighter v2.7.1\n[product_page sku=”ART103″]\n1\n[product_page sku=“ART103”]\n[product_category]\nShows the products in a category which are specified by their permalink (slug). You can find the permalink in the dashboard under Products → Categories in the column Permalink.\nParameter\nper_page default: 12 Number of products displayed per page. columns default: 4 Number of columns. orderby default: title Sort key. order default: desc Sort order. category default: ” Category slug. Example\nCrayon Syntax Highlighter v2.7.1\n[product_category category=”musik”]\n1\n[product_category category=“musik”]\n[product_categories]\nDisplays the product categories with the category image and if desired the number of products contained in each of the categories.\nParameter\nnumber default: null Number of categories to be displayed. If null, then all are displayed. columns default: 4 Number of columns. orderby default: name Sort key. order default: asc Sort order. hide_empty default: 1 Specifies whether or not to display empty categories. 1 for yes, 0 for no. parent default: ” If set to 0, only top level categories will appear. ids default: ” The Ids of categories to be displayed. If not specified, all categories will be included. Example\nCrayon Syntax Highlighter v2.7.1\n[product_categories number=”12″ parent=”0″]\n1\n[product_categories number=“12” parent=“0”]\n[sale_products]\nShows the products that are currently on offer, sorted according to various criteria. For presentation purposes you can specify the number of products to be displayed per page and the number of columns.\nParameter\nper_page default: 12 Number of products displayed per page. columns default: 4 Number of columns. orderby default: title Sort key. order default: asc Sort order. Example\nCrayon Syntax Highlighter v2.7.1\n[sale_products per_page=”12″]\n1\n[sale_products per_page=“12”]\n[best_selling_products]\nShows best-selling products. The number of products displayed per page and the number of columns can be specified here.\nParameter\nper_page default: 12 Number of products displayed per page. columns default: 4 Number of columns. Example\nCrayon Syntax Highlighter v2.7.1\n[best_selling_products per_page=”12″]\n1\n[best_selling_products per_page=“12”]\n[top_rated_products]\nShows top-rated products. Sorting according to various criteria possible.\nParameter\nper_page default: 12 Number of products displayed per page. columns default: 4 Number of columns. orderby default: title Sort key. order default: asc Sort order. Example\nCrayon Syntax Highlighter v2.7.1\n[top_rated_products per_page=”12″]\n1\n[top_rated_products per_page=“12”]\n[product_attribute]\nShows products with a particular property and the specified values for that property. Sorting according to various criteria possible.\nParameter\nper_page default: 12 Number of products displayed per page. columns default: 4 Number of columns. orderby default: title Sort key. order default: asc Sort order. attribute default: ” The property that the products must have in order to be displayed. They will only appear if the parameter is used. filter default: ” The value of the property the products must possess in order to be displayed. They will only appear if the parameter is used. Example\nCrayon Syntax Highlighter v2.7.1\n[product_attribute attribute=”farbe” filter=”schwarz”]\n1\n[product_attribute attribute=“farbe” filter=“schwarz”]\n[related_products]\nShows similar products. Similar products are determined on the basis of categories and tags. This shortcode must be used within a product detail page.\nParameter\nper_page default: 2 Number of products displayed per page. columns default: 2 Number of columns. orderby default: rand Sort key. Example\nCrayon Syntax Highlighter v2.7.1\n[related_products per_page=”12″ orderby=”title”]\n1\n[related_products per_page=“12” orderby=“title”]\nCaution: The per_page parameter specifies how many items to display on a page. The pagination function is not automatically generated. The per_page and columns parameters determine how many products and columns will be displayed. Whether this actually works and for which parameter values, is highly dependent on the layout of your theme. This requires some trial and error and reworking of the CSS.\nThe original documentation can be found on these WooThemes pages. Some shortcodes have been removed since WooCommerce 2.1.x. These shortcodes have not been described here. If required, you can also find them in the WooThemes documentation.\n","date":"15 April 2016","externalUrl":null,"permalink":"/woocommerce-shortcodes/","section":"Articles","summary":"The first four shortcodes are used for special WooCommerce pages and are sometimes automatically inserted into the pages by WooCommerce during installation. They should not otherwise be used. All others can be used throughout and can be used more than once.\n","title":"WooCommerce Shortcodes","type":"articles"},{"content":"","date":"27 February 2016","externalUrl":null,"permalink":"/categories/blog/","section":"Categories","summary":"","title":"Blog","type":"categories"},{"content":"So I’ve been volunteering for an NGO called Otra Cosa Network in Peru and as part of my volunteering I have been teaching young children to swim, but of course I get roped into helping with their website. A busman’s holiday I know..!\nSo their existing website is using Joomla so the first step for me is to back a backup copy of the existing Joomla website.\nI found JoomlaPack, which is now called Keeba Backup, which can be found here:\nhttps://www.akeebabackup.com/download.html\nThey recommend you follow the videos on their website\nhttps://www.akeebabackup.com/videos/1212-akeeba-backup-core/1615-abtc01-installation-first-backup.html\nNow that you are able to backup the website, I needed to restore the live website to backup site, to do this you need to download Keeba KickStart and unzip the files, taking just the kickstart.php file which you’ll need to add to the root folder of the new website, also copy across the backup file you wish to restore.\nA backup of your web site is only useful if you can restore it – perhaps you need to transfer your web host or even move the site from a development server to a live server.\nLike always I have attached the version I worked with at the bottom of this post.\nHere is a step by step process for you to restore the backup you have just taken:\nOr you can watch the video here\nTo begin with, take a brand new backup of your web site. Once the backup is complete, go to Manage Backups and download the backup file to your computer. Now we’ve downloaded the backup file, we need an additional program called Kickstart which you can find at the akeebabackup.com web site. Go to downloads. Scroll down to Akeeba Kickstart and click Download to download the file to your computer. The Kickstart program is NOT a Joomla extension. Here we can see that the Kickstart program is a zip file and we need to extract that. On most operating systems you can do that simply by double clicking on the file name. We can see we now have a new folder with all the kickstart files in it. The only one that you actually need is the kickstart.php file; all the rest are language translations. We now need to transfer the kickstart.php and our backup to our brand new web host, and to do that we will use a FTP program. I am going to use filezilla but you can use any ftp program that you like. To begin with, connect to your NEW server. Once connected, make sure you are in the public html or the web root of your server. Now you need to transfer the backup file from our local computer to our live server. I am just going to pick that up and drag it across. You can see the upload is taking place. We now have the backup file on the new server. We now need to take that kickstart.php file and do exactly the same thing. Select it and drag it across. That’s it with the filezilla for now so let’s go back to our web browser and go to our brand new web site. As you can see I have a holding page in place to show that the web site is coming soon. So just go to the special url for kickstart.php. The kickstart program is now running. Kickstart is NOT an installation program, it is a special archive extraction tool. We can click here to remove this message and we can see here that it has detected the archive file. We have several methods of extracting the files. On most good web hosts, we can use the hybrid method. Finally click START to begin the extract process. Kickstart has now extracted the backup file and provides a link to the installer that was built in to that backup. The installer is a very simple process. We begin with the required settings. As you can see, they are all set to yes. If any are set to No, you won’t be able to proceed and you need to speak to your web hosts to rectify the errors. We can now click Next. I know need to enter the database connection details that I have got from my web host. Enter the server hostname (which is usually localhost, but that may depend on your hosting) and your DATABASE username and password. And finally the database name that you want to install your web site on. Again this is something that your host will have provided to you or you will have set up yourself within your hosts control panel. And click next. The restoration process of the database has now been processed and we can click to continue. We have now have the opportunity if we wish to change the site name and the email address. In most cases when you are restoring a site you won’t need to do this. If we scroll down there is also the opportunity to change the password and email address of the Super Administrator. Finally, click Next again. The sites configuration has all been setup. Now what we need to do is close this window and when we are now back at the Akeeba Kickstart program and click on Cleanup. This will remove the kickstart.php file and that big backup archive. Now that we’re done we can visit our website and here we can see that the web site has now been transferred from our old hosting account to our new one. com_akeeba-4.5.5-core.zip (2.48 mb)\nkickstart-core-4.1.4.zip (267.22 kb)\n","date":"27 February 2016","externalUrl":null,"permalink":"/how-to-move-a-joomla-website/","section":"Articles","summary":"So I’ve been volunteering for an NGO called Otra Cosa Network in Peru and as part of my volunteering I have been teaching young children to swim, but of course I get roped into helping with their website. A busman’s holiday I know..!\n","title":"How to move a Joomla website","type":"articles"},{"content":"","date":"27 February 2016","externalUrl":null,"permalink":"/categories/joomla/","section":"Categories","summary":"","title":"Joomla","type":"categories"},{"content":"Problem I have created a view that posts to an action via Ajax with the expectation that the action will return the requested data or an empty string. Even better, I would like it to be configurable to return whatever value I see fit.\nThe problem arises when I decorate the called action with the [Authorize] attribute. If the request is not authorized and I have a loginUrl configured in my web.config, my ajax request will return the html output of my loginUrl view. That is undesirable.\nSolution I can extend the existing Authorize attribute by inheriting from the AuthorizeAttribute class. Here is the code that extends the Authorize attribute:\npublic class AjaxAuthorizeOverrideAttribute : AuthorizeAttribute { public string View { get; set; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.Request.IsAjaxRequest()) { base.HandleUnauthorizedRequest(filterContext); return; } filterContext.Result = new ViewResult { ViewName = View }; filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext); } }\u0026lt;/pre\u0026gt; Here is the decorator for the ajax action in the controller class:\n[AjaxAuthorizeOverride(View=\"AjaxAuthorizeError\")] public ActionResult AjaxRequest() { return View(); }\nNote: there is no default view page being rendered.\nOriginal article can be found here\n","date":"18 December 2014","externalUrl":null,"permalink":"/the-way-to-handle-unauthorised-requests-to-ajax-actions-in-asp-net-mvc/","section":"Articles","summary":"Problem I have created a view that posts to an action via Ajax with the expectation that the action will return the requested data or an empty string. Even better, I would like it to be configurable to return whatever value I see fit.\n","title":"The way to handle unauthorised requests to Ajax actions in ASP.NET MVC","type":"articles"},{"content":"Now that we have a Nuget Server installed and up and running we will want to deploy our packages.\nFirst you’ll need to install the nuget.exe command line bootstrapper\nInstalling NuGet.exe Download NuGet.exe Place NuGet in a well known location such as c:\\utils on your machine Make sure that NuGet.exe is in your path Then you can take two simple steps to generate your package\nnuget pack MyProject.csproj -IncludeReferencedProjects -Prop Configuration=Release then push your pack to the nuget server, with your APIKey you setup in your web.config of the nuget.server\nnuget push {package file} -s http://yourNugetServer/ {apikey} That is it, you now have your package available in your own private nuget server.\nFor more details on Creating and Publishing a Package\n","date":"23 May 2014","externalUrl":null,"permalink":"/creating-and-publishing-to-nuget/","section":"Articles","summary":"Now that we have a Nuget Server installed and up and running we will want to deploy our packages.\nFirst you’ll need to install the nuget.exe command line bootstrapper\nInstalling NuGet.exe Download NuGet.exe Place NuGet in a well known location such as c:\\utils on your machine Make sure that NuGet.exe is in your path Then you can take two simple steps to generate your package\n","title":"Creating and Publishing to NuGet","type":"articles"},{"content":"","date":"23 May 2014","externalUrl":null,"permalink":"/categories/nuget/","section":"Categories","summary":"","title":"NuGet","type":"categories"},{"content":"Whether it’s your company restricts which third-party libraries their developers may use or just you need your own private repository to store all your protected work. A NuGet Server is what you are after.\nBefore I start I need to mention a few things about NuGet Gallery, which I spent a good two days trying to get working correctly on Azure and failed and in the end ended up generating a very basic Nuget Server to host all the libraries.\nThis all can be done with just four simple steps\nCreate a new DotNet Core ASP.net Web MVC Application Install nuget.server (https://www.nuget.org/packages/NuGet.Server.Core/) Deploy your application to your website That is it, if you fire up your server you should see a screen like this:\nThat is it you now have a hosted Nuget Server, next we’ll look at deploying your solution to the Nuget Server\nFull details can be found here: Host Your Own NuGet Server or How To Create Local NuGet Server\n","date":"23 May 2014","externalUrl":null,"permalink":"/setting-up-a-nuget-server/","section":"Articles","summary":"Whether it’s your company restricts which third-party libraries their developers may use or just you need your own private repository to store all your protected work. A NuGet Server is what you are after.\nBefore I start I need to mention a few things about NuGet Gallery, which I spent a good two days trying to get working correctly on Azure and failed and in the end ended up generating a very basic Nuget Server to host all the libraries.\n","title":"Setting up a NuGet Server","type":"articles"},{"content":"Here are some helpful pointers for writing User Stories\nA Story template “As a \u0026lt;User or role\u0026gt; I want \u0026lt;Business Functionality\u0026gt; So that \u0026lt;Business Justification\u0026gt;” Example: As a Account Holder, I want to be able to withdraw funds from my checking account, So that I can buy some bling. Stories are not “mini” Use Cases a complete specification a contract intended to be interpreted without a Product Owner User Stories guidelines Testable – Tangible acceptance tests can be written against any delivered software The scope of the User Story is manage-able enough for the team to provide an Estimate Independent and do not rely on other Stories Sized appropriately.. Have a level of effort which the team can comfortably achieve in the duration of a single iteration More information can be found http://www.mountaingoatsoftware.com/agile/user-stories ","date":"20 May 2014","externalUrl":null,"permalink":"/user-stories/","section":"Articles","summary":"Here are some helpful pointers for writing User Stories\n","title":"User Stories","type":"articles"},{"content":"Unless you’re a one person web shop with no team to collaborate with, you’ve experienced the frustration that goes along with file sharing. No matter how hard you try, when multiple people are working on a single project without a version control system in place things get chaotic.\nIf you work with developers on the build-out and implementation of websites, the merge between front-end templates and back-end functionality can be a scary black hole.\nIssues like overwrites, lost files, and the all-too-common “working off a previous version” phenomenon crop up constantly. And once back-end functionality has been put into your templates, you become terrified to touch them for fear of breaking something a developer spent a great deal of time getting to work.\nIn addition, even if you have a common repository that everyone is pulling from odds are at least one member of your team forgot to grab the latest files and is about to blow things up with their latest additions.\nFear not GitHub is here to save the day, I’ll give you a quick review of GitHub, an excellent version control system.\nVersion Control – A Quick and Dirty Explanation Version Control (also known as Revision Control or Source Control Management) is a great way to solve the file sharing problem.\nThe basic concept is this: there is one main repository for all of the project files. Team members check files out, make changes, and then check them back in (or commit them). The Version Control System (VCS) automatically notes who changed the files, when they were changed, and what about them was new or different.\nIt also asks you to write a little note about the change so everyone on the project knows at a glance what you did and why. Each file will then have a revision history so you can easily go back to a previous version of any file if something goes horribly wrong.\nA good Version Control System also allows you to merge changes to the same file. If you and another person work locally on the same file at the same time, when you push these files back into the main repository the system will merge both sets of changes to create a new and fully up-to-date file. If any conflicts arise during the merge it will highlight them for you.\nYou’re probably using a very crude Version Control System right now to keep your files straight. If you’re a designer, it looks something like this:\nThis works well enough for PSDs and other large binary files, which don’t really lend themselves to Version Control System. But there’s a much better way to do it when you are managing the source code for a website.\nBenefits to using a Version Control System include: Files cannot be overwritten There is a common repository that holds all the latest files People can work on the same files simultaneously without conflict Allows you to revert back to an older version of the file/project if needed Making your developers very happy Even if you don’t work with a team, version control can be a lifesaver. Backing up files is one of the easiest things you can do to save yourself from losing work or having to start over.\nThe idea of a Version Control System seems daunting at first, especially since most of the documentation is written by and for developers. But once you make the move to incorporate it into your workflow, you’ll find it’s not nearly as hard as it looks.\nMeet GitHub OK, so now you can see why a Version Control System is a must-have for your web team. If you do a little Googling you’ll see that there are quite a few options out there including SVN, Mercurial, CVS, Bazaar and GitHub. Any one of them could be a good solution for your needs, and I encourage you to do some research before selecting a Version Control System. In this article I’m going to focus on GitHub, the one I use daily. It’s a “rising star” that has gained popularity thanks to a strong Linux fanbase, GitHub and the Rails community.\nGitHub is a free open-source Version Control System originally created by Linus Torvalds for Linux kernal development. Linus is a very smart guy; when he sets out to solve a problem, he doesn’t mess around. One of Git’s big differentiators is that unlike SVN and CVS it is a distributed version control system. This means that every user has a complete copy of the repository data stored locally on their machine. What’s so great about that? A few things:\nEverything is local, so you can work offline There is no single point of failure. It doesn’t rely on one central server that could crash and burn, taking the only repository for your project with it. Because it doesn’t have to communicate with a central server constantly, processes run much faster Git has a slightly tougher learning curve than SVN, but the trade-off is worth it. Just think how impressed your developer friends will be when you tell them you’re using the new hotness that is Git! In all seriousness, I don’t think the learning curve is all that steep. Installing Git isn’t fun and games. But there are plenty of resources online to get you through it. It will run on a PC, Mac or Linux box, although installation for Linux and OSX is considerable easier than for Windows.\nYou can download the latest version of Git here. Once you have the files, try this quick guide to get you started with the installation process. For Windows users, this step-by-step visual guide should be helpful. Mac users, try this guide found on GitHub\nOriginal Article\n","date":"25 March 2014","externalUrl":null,"permalink":"/github-for-web-designers/","section":"Articles","summary":"Unless you’re a one person web shop with no team to collaborate with, you’ve experienced the frustration that goes along with file sharing. No matter how hard you try, when multiple people are working on a single project without a version control system in place things get chaotic.\n","title":"GitHub for web Designers","type":"articles"},{"content":"","date":"8 March 2014","externalUrl":null,"permalink":"/categories/asp.net-identity/","section":"Categories","summary":"","title":"ASP.NET Identity","type":"categories"},{"content":"So how do you obtain the external user email (the one authentication by google), first name and name in an ASP.NET website using ASP.NET Identity?\nvar email = externalIdentity.FindFirstValue(ClaimTypes.Email); and here is getting the type\npublic static string FindFirstValue(this ClaimsIdentity identity, string claimType) { Claim claim = identity.FindFirst(claimType); if (claim != null) { return claim.Value; } return null; } For more information take a look at Decoupling OWIN external authentication from ASP.NET Identity\n","date":"8 March 2014","externalUrl":null,"permalink":"/google-authentication-get-email-from-asp-net-identity/","section":"Articles","summary":"So how do you obtain the external user email (the one authentication by google), first name and name in an ASP.NET website using ASP.NET Identity?\nvar email = externalIdentity.FindFirstValue(ClaimTypes.Email); and here is getting the type\n","title":"Google authentication get email from ASP.NET Identity","type":"articles"},{"content":"I can’t believe I couldn’t find a working solution to this after an hour of searching. I’m following this articleon Entity Framework 6.0 which gives a simple walk-through on Code First. I created the project and installed the latest EF Nuget package for the project to compile. I also verified that I have Microsoft SQL Server 2012 Express LocalDB installed which came with Visual Studio 2013. I don’t have any other instances of SQL installed on my local computer. The program runs and entries are added to the database and outputted in the console. But when the article says “check your localdb” it doesn’t say how! I don’t see any ‘.mdf’ or ‘.ldf’ files created under the project folder. I tried every way to connect Visual Studio’s Server Explorer to LocalDB. The wizard cannot locate (localdb) or cannot find any provider in Server Explorer to accept connection string like (localdb)\\v11.0;Integrated Security=true;\" I’ve seen this asked several places in StackOverflow but no answer works or marked as answer. Please help, this doesn’t have to be this frustrating!\nWhat are the steps to connect Visual Studio Server Explorer to LocalDB?\nSteps to connect LocalDB to Visual Studio Server Explorer\nOpen command prompt Run SqlLocalDB.exe start v11.0 Run SqlLocalDB.exe info v11.0 Copy the Instance pipe name that starts with np:\\… In Visual Studio select TOOLS \u0026gt; Connect to Database… For Server Name enter (localdb)\\v11.0. If it didn’t work, use the Instance pipe name that you copied earlier. You can also use this to connect with SQL Management Studio. Select the database on next dropdown list Click OK ","date":"5 March 2014","externalUrl":null,"permalink":"/ttt/","section":"Articles","summary":"I can’t believe I couldn’t find a working solution to this after an hour of searching. I’m following this articleon Entity Framework 6.0 which gives a simple walk-through on Code First. I created the project and installed the latest EF Nuget package for the project to compile. I also verified that I have Microsoft SQL Server 2012 Express LocalDB installed which came with Visual Studio 2013. I don’t have any other instances of SQL installed on my local computer. The program runs and entries are added to the database and outputted in the console. But when the article says “check your localdb” it doesn’t say how! I don’t see any ‘.mdf’ or ‘.ldf’ files created under the project folder. I tried every way to connect Visual Studio’s Server Explorer to LocalDB. The wizard cannot locate (localdb) or cannot find any provider in Server Explorer to accept connection string like (localdb)\\v11.0;Integrated Security=true;\" I’ve seen this asked several places in StackOverflow but no answer works or marked as answer. Please help, this doesn’t have to be this frustrating!\n","title":"ttt","type":"articles"},{"content":"The online MSDN documentation is your first source for things like that:\nRead about the ServiceContractAttribute Read about the OperationContractAttribute Read about the DataContractAttribute All the MSDN documentation pages contain detailed explanations of all the settings on those contract attributes.\n","date":"2 February 2014","externalUrl":null,"permalink":"/wcf-attributes-and-what-they-all-mean/","section":"Articles","summary":"The online MSDN documentation is your first source for things like that:\n","title":"WCF Attributes and what they all mean","type":"articles"},{"content":"If you have used Bootstrap with your ASP.NET MVC application, you might have faced some issues with implementing active links of it’s Navbar component. We’ll have to dynamically add a css class called active to the particular menu item in order to make it selected in the Navbar. Here is a HtmlHelper extension which is capable of rendering menu items as well as drop-down menu items. I’ve used ASP.NET MVC 5 with Razor and Bootstrap 3.\nFirst step is to create a HtmlHelper extension class. using System.Web.Mvc; public static class MenuLinkExtension { public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper, string itemText, string actionName, string controllerName, MvcHtmlString[] childElements = null) { var currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString(\u0026ldquo;action\u0026rdquo;); var currentController = htmlHelper.ViewContext.RouteData.GetRequiredString(\u0026ldquo;controller\u0026rdquo;); string finalHtml; var linkBuilder = new TagBuilder(\u0026ldquo;a\u0026rdquo;); var liBuilder = new TagBuilder(\u0026ldquo;li\u0026rdquo;);\nif (childElements != null \u0026amp;amp;\u0026amp;amp; childElements.Length \u0026amp;gt; 0) { linkBuilder.MergeAttribute(\u0026quot;href\u0026quot;, \u0026quot;#\u0026quot;); linkBuilder.AddCssClass(\u0026quot;dropdown-toggle\u0026quot;); linkBuilder.InnerHtml = itemText + \u0026quot; \u0026amp;lt;b class=\\\u0026quot;caret\\\u0026quot;\u0026amp;gt;\u0026amp;lt;/b\u0026amp;gt;\u0026quot;; linkBuilder.MergeAttribute(\u0026quot;data-toggle\u0026quot;, \u0026quot;dropdown\u0026quot;); var ulBuilder = new TagBuilder(\u0026quot;ul\u0026quot;); ulBuilder.AddCssClass(\u0026quot;dropdown-menu\u0026quot;); ulBuilder.MergeAttribute(\u0026quot;role\u0026quot;, \u0026quot;menu\u0026quot;); foreach (var item in childElements) { ulBuilder.InnerHtml += item + \u0026quot;\\n\u0026quot;; } liBuilder.InnerHtml = linkBuilder + \u0026quot;\\n\u0026quot; + ulBuilder; liBuilder.AddCssClass(\u0026quot;dropdown\u0026quot;); if (controllerName == currentController) { liBuilder.AddCssClass(\u0026quot;active\u0026quot;); } finalHtml = liBuilder.ToString() + ulBuilder; } else { var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection); linkBuilder.MergeAttribute(\u0026quot;href\u0026quot;, urlHelper.Action(actionName, controllerName)); linkBuilder.SetInnerText(itemText); liBuilder.InnerHtml = linkBuilder.ToString(); if (controllerName == currentController \u0026amp;amp;\u0026amp;amp; actionName == currentAction) { liBuilder.AddCssClass(\u0026quot;active\u0026quot;); } finalHtml = liBuilder.ToString(); } return new MvcHtmlString(finalHtml); } }\nOnce you have saved it, you can it by just calling like this!\n\u0026lt;header class=\"navbar navbar-inverse navbar-fixed-top bs-docs-nav\" role=\"banner\"\u0026gt; \u0026lt;div class=\"container\"\u0026gt; \u0026lt;div class=\"navbar-header\"\u0026gt; \u0026lt;a href=\"#\" class=\"navbar-brand\"\u0026gt;Mvc Shop\u0026lt;/a\u0026gt; \u0026lt;/div\u0026gt; \u0026lt;nav role=\"navigation\"\u0026gt; \u0026amp;lt;ul class=\u0026quot;nav navbar-nav\u0026quot;\u0026amp;gt; @Html.MenuLink(\u0026quot;Home\u0026quot;, \u0026quot;Index\u0026quot;, \u0026quot;Home\u0026quot;) @Html.MenuLink(\u0026quot;Dropdown\u0026quot;, \u0026quot;Index\u0026quot;, \u0026quot;Home2\u0026quot;, new MvcHtmlString[]{ @Html.MenuLink(\u0026quot;Link1\u0026quot;, \u0026quot;Action1\u0026quot;, \u0026quot;Controller1\u0026quot;), @Html.MenuLink(\u0026quot;Link2\u0026quot;, \u0026quot;Action2\u0026quot;, \u0026quot;Controller1\u0026quot;), @Html.MenuLink(\u0026quot;Link3\u0026quot;, \u0026quot;Action3\u0026quot;, \u0026quot;Controller1\u0026quot;), }) @Html.MenuLink(\u0026quot;JavaScript\u0026quot;, \u0026quot;Index\u0026quot;, \u0026quot;Home1\u0026quot;, new MvcHtmlString[]{ @Html.MenuLink(\u0026quot;Link1\u0026quot;, \u0026quot;Index1\u0026quot;, \u0026quot;Home1\u0026quot;), @Html.MenuLink(\u0026quot;Link2\u0026quot;, \u0026quot;Index2\u0026quot;, \u0026quot;Home1\u0026quot;), @Html.MenuLink(\u0026quot;Link3\u0026quot;, \u0026quot;Index3\u0026quot;, \u0026quot;Home1\u0026quot;) }) \u0026amp;lt;/ul\u0026amp;gt; \u0026amp;lt;/nav\u0026amp;gt; \u0026amp;lt;/div\u0026amp;gt; \u0026lt;/header\u0026gt;\n","date":"20 January 2014","externalUrl":null,"permalink":"/active-links-on-bootstrap-navbar-with-asp-net-mvc/","section":"Articles","summary":"If you have used Bootstrap with your ASP.NET MVC application, you might have faced some issues with implementing active links of it’s Navbar component. We’ll have to dynamically add a css class called active to the particular menu item in order to make it selected in the Navbar. Here is a HtmlHelper extension which is capable of rendering menu items as well as drop-down menu items. I’ve used ASP.NET MVC 5 with Razor and Bootstrap 3.\n","title":"Active links on Bootstrap Navbar with ASP.NET MVC","type":"articles"},{"content":"","date":"20 January 2014","externalUrl":null,"permalink":"/categories/bootstrip/","section":"Categories","summary":"","title":"Bootstrip","type":"categories"},{"content":"I have always used a ranked search criteria, it’s the only true way to get good results back from a data set. But I’ve been doing my ranking within C# code. But this got all the data from the data source and then ranked the results. This is very poor on performance, as we should only be returning back the results for the page size we require.\nSo task at hand it to produce a LINQ statement to reterive only the data you require.\nHere is the solution:\nvar entity = new myEntities(); var searchTerm = \u0026ldquo;a b Ba\u0026rdquo;;\nvar searchArray = searchTerm.Split(new[] { \u0026rsquo; \u0026rsquo; }, StringSplitOptions.RemoveEmptyEntries);\nvar usersAll = entity.User.AsExpandable().Where(TC_User.ContainsInLastName(searchArray));\nConsole.WriteLine(\u0026ldquo;Total Records: {0}\u0026rdquo;, usersAll.Count());\nvar users = usersAll .Select(x =\u0026gt; new { x.LastName, Rank = searchArray.Sum(s =\u0026gt; ((x.LastName.Length - x.LastName.Replace(s, \u0026ldquo;\u0026rdquo;).Length) / s.Length)) });\nvar results = users.OrderByDescending(o =\u0026gt; o.Rank) .Skip(0) .Take(20);\nforeach (var user in results) { Console.WriteLine(\u0026quot;{0}, {1}\u0026quot;, user.LastName, user.Rank); }\nConsole.ReadLine();\nYou’ll also need to add a new method to your User class to check for that the search term is contain in the LastName\npublic static Expression\u0026lt;Func\u0026lt;TC_User, bool\u0026gt;\u0026gt; ContainsInLastName( params string[] keywords) { var predicate = PredicateBuilder.False\u0026lt;TC_User\u0026gt;(); foreach (string keyword in keywords) { string temp = keyword; predicate = predicate.Or(p =\u0026gt; p.LastName.Contains(temp)); } return predicate; } One thing that is required is LinqKit, which is available via NuGet to handle the PredicateBuilder and AsExpandable.\nWatch out as the results coming back from Sum is a BigInt so if you create a model to return back make sure it is a long type.\n","date":"31 December 2013","externalUrl":null,"permalink":"/how-to-rank-your-search-results-with-multiple-search-terms-using-linq-and-entityframework/","section":"Articles","summary":"I have always used a ranked search criteria, it’s the only true way to get good results back from a data set. But I’ve been doing my ranking within C# code. But this got all the data from the data source and then ranked the results. This is very poor on performance, as we should only be returning back the results for the page size we require.\n","title":"How to Rank your search results with multiple search terms using LINQ and EntityFramework","type":"articles"},{"content":"","date":"31 December 2013","externalUrl":null,"permalink":"/categories/linq/","section":"Categories","summary":"","title":"LINQ","type":"categories"},{"content":"","date":"31 December 2013","externalUrl":null,"permalink":"/categories/linq2sql/","section":"Categories","summary":"","title":"LINQ2SQL","type":"categories"},{"content":"There are a number of options for backing up SQL Azure, which can be found here:\nDifferent ways to Backup your Windows Azure SQL Database\nI like the Azure way, which is just exporting, importing and setting a scheduled\nBefore You Begin The SQL Database Import/Export Service requires you to have a Windows Azure storage account because BACPAC files are stored here. For more information about creating a storage account, see How to Create a Storage Account. You must also create a container inside Blob storage for your BACPAC files by using a tool such as the Windows Azure Management Tool (MMC) or Azure Storage Explorer.\nIf you want to import an on-premise SQL Server database to Windows Azure SQL Database, first export your on-premise database to a BACPAC file, and then upload the BACPAC file to your Blob storage container.\nIf you want to export a database from Windows Azure SQL Database to an on-premise SQL Server, first export the database to a BACPAC file, transfer the BACPAC file to your local server (computer), and then import the BACPAC file to your on-premise SQL Server.\nExport a Database Using one of the tools listed in the Before You Begin section, ensure that your Blob has a container.\nLog on to the Windows Azure Platform Management Portal.\nIn the navigation pane, click Hosted Services, Storage Accounts \u0026amp; CDN, and then click Storage Accounts. Your storage accounts display in the center pane.\nSelect the required storage account, and make a note of the following values from the right pane: Primary access key and BLOB URL. You will have to specify these values later in this procedure.\nIn the navigation pane, click Database. Next, select the subscription, your SQL Database server, and then your database that you want to export.\nOn the ribbon, click Export. This opens the Export Database to Storage Account window.\nVerify that the Server Name and Database match the database that you want to export.\nIn the Login and Password boxes, type the database credentials to be used for the export. Note that the account must be a server-level principal login – created by the provisioning process – or a member of the dbmanager database role.\nIn New Blob URL box, specify the location where the exported BACPAC file is saved. Specify the location in the following format: “https://” + Blob URL (as noted in step 4) + “/\u0026lt;container_name\u0026gt;/\u0026lt;file_name\u0026gt;”. For example: https://myblobstorage.blob.core.windows.net/dac/exportedfile.bacpac. The Blob URL must be in lowercase without any special characters. If you do not supply the .bacpac suffix, it is applied by the export operation.\nIn the Access Key box, type the storage access key or shared access key that you made a note of in step 4.\nFrom the Key Type list, select the type that matches the key entered in the Access Key box: either a Storage Access Key or a Shared Access Key.\nClick Finish to start the export. You should see a message saying Your request was successfully submitted.\nAfter the export is complete, you should attempt to import your BACPAC file into a Windows Azure SQL Database server to verify that your exported package can be imported successfully.\nDatabase export is an asynchronous operation. After starting the export, you can use the Import Export Request Status window to track the progress. For information, see How to: View Import and Export Status of Database (Windows Azure SQL Database).\nNote An export operation performs an individual bulk copy of the data from each table in the database so does not guarantee the transactional consistency of the data. You can use the Windows Azure SQL Database copy database feature to make a consistent copy of a database, and perform the export from the copy. For more information, see Copying Databases in Windows Azure SQL Database. Configure Automated Exports Use the Windows Azure SQL Database Automated Export feature to schedule export operations for a SQL database, and to specify the storage account, frequency of export operations, and to set the retention period to store export files.\nTo configure automated export operations for a SQL database, use the following steps:\nLog on to the Windows Azure Platform Management Portal.\nClick the SQL database name you want to configure, and then click the Configuration tab.\nOn the Automated Export work space, click Automatic, and then specify settings for the following parameters:\nStorage Account Frequency Specify the export interval in days. Specify the start date and time. The time value on the configuration work space is UTC time, so note the offset between UTC time and the time zone where your database is located. Credentials for the server that hosts your SQL database. Note that the account must be a server-level principal login – created by the provisioning process – or a member of the dbmanager database role. When you have finished setting the export settings, click Save.\nYou can see the time stamp for the last export on under Automated Export in the Quick Glance section of the SQL Database Dashboard.\nTo change the settings for an automated export, select the SQL database, click the Configuration tab, make your changes, and then click Save.\nCreate a New SQL Database from an Existing Export File Use the Windows Azure SQL Database Create from Export feature to create a new SQL database from an existing export file.\nTo create a new SQL database from an existing export file, use the following steps:\nLog on to the Windows Azure Platform Management Portal.\nClick a SQL database name and then click the Configuration tab.\nOn the Create from Export work space, click New Database, and then specify settings for the following parameters:\nBacpac file name – This is the source file for your new SQL database. A name for the new SQL database. Server – This is the host server for your new SQL database. To start the operation, click the checkmark at the bottom of the page. Import and Export a Database Using API You can also programmatically import and export databases by using an API. For more information, see the Import Export example on Codeplex.\nImport a Database Using one of the tools listed in the Before You Begin section, ensure that your Blob has a container, and the BACPAC file to be imported is available in the container.\nLog on to the Windows Azure Platform Management Portal.\nIn the navigation pane, click Hosted Services, Storage Accounts \u0026amp; CDN, and then click Storage Accounts. Your storage accounts display in the center pane.\nSelect the storage account that contains the BACPAC file to be imported, and make a note of the following values from the right pane: Primary access key and BLOB URL. You will have to specify these values later in this procedure.\nIn the navigation pane, click Database. Next, select the subscription, and then your SQL Database server where you want to import the database.\nOn the ribbon, click Import. This opens the Import Database from Storage Account window.\nVerify that the Target Server field lists the SQL Database server where the database is to be created.\nIn the Login and Password boxes, type the database credentials to be used for the import.\nIn the New Database Name box, type the name for the new database created by the import. This name must be unique on the SQL Database server and must comply with the SQL Server rules for identifiers. For more information, see Identifiers.\nFrom the Edition list, select whether the database is a Web or Business edition database.\nFrom the Maximum Size list, select the required size of the database. The list only specifies the values supported by the Edition you have selected.\nIn the BACPAC URL box, type the full path of the BACPAC file that you want to import. Specify the path in the following format: “https://” + Blob URL (as noted in step 4) + “/\u0026lt;container_name\u0026gt;/\u0026lt;file_name\u0026gt;”. For example: https://myblobstorage.blob.core.windows.net/dac/file.bacpac. The Blob URL must be in lowercase without any special characters. If you do not supply the .bacpac suffix, it is applied by the import operation.\nIn the Access Key box, type the storage access key or shared access key that you made a note of in step 4.\nFrom the Key Type list, select the type that matches the key entered in the Access Key box: either a Storage Access Key or a Shared Access Key.\nClick Finish to start the import.\nDatabase import is an asynchronous operation. After starting the import, you can use the Import Export Request Status window to track the progress. For information, see How to: View Import and Export Status of Database (Windows Azure SQL Database).\nOriginal Article\n","date":"28 December 2013","externalUrl":null,"permalink":"/backup-sql-azure/","section":"Articles","summary":"There are a number of options for backing up SQL Azure, which can be found here:\nDifferent ways to Backup your Windows Azure SQL Database\nI like the Azure way, which is just exporting, importing and setting a scheduled\n","title":"Backup SQL Azure","type":"articles"},{"content":"What is Vertical And Horizontal Privilege Escalation? Does your application support for this internally authorisation verification of work? I expect not, it is really an over sight of the architecture and application planning that this is missed out and more importantly when it becomes an issue it is more often than not too late to implement any changes.\nSo what is Vertical And Horizontal Privilege Escalation? Privilege escalation is the act of exploiting a bug, design flaw or configuration oversight in an operating system or software application to gain elevated access to resources that are normally protected from an application or user. The result is that an application with more privileges than intended by the application developer or system administrator can perform unauthorized actions.\nYou may find that you have alternative methods to protect against privilege escalation:\nAuthorize attribute: This is used to authorize a user or role to access any resource in the application after authenticated. This helps to have User and Role level protections. Http Referrer Check: This is to prevent an URL request which is not from the site, but from an external link or the link directly executed at the browser navigation Anti Forgery Token: This is a powerful option to prevent any hidden field manipulation while form posting and prevents Cross-Site Request Forgery HTML Encoding: It is advised to encode all user inputs to prevent Cross Site Scripting attack/ XSS attack etc., Encryption of Query string parameters. This is good way to prevent manipulation of query string parameters. URL Activity Tampering, we provide a key in the URL that can only be used for that URL Even though you may not support Privilege Escalation directly you can place a front line of defence, Privilege escalation means a user receives privileges they are not entitled to. These privileges can be used to change information, view private information, or install unwanted programs such as viruses. It usually occurs when a system has a bug that allows security to be bypassed or, alternatively, has flawed design assumptions about how it will be used. Privilege escalation occurs in two forms:\nVertical privilege escalation, also known as privilege elevation, where a lower privilege user or application accesses functions or content reserved for higher privilege users or applications Horizontal privilege escalation, where a normal user accesses functions or content reserved for other normal users I hope this help you understand, that planning and understanding issues from the outset is so important. ","date":"19 December 2013","externalUrl":null,"permalink":"/vertical-and-horizontal-privilege-escalation/","section":"Articles","summary":"What is Vertical And Horizontal Privilege Escalation? Does your application support for this internally authorisation verification of work? I expect not, it is really an over sight of the architecture and application planning that this is missed out and more importantly when it becomes an issue it is more often than not too late to implement any changes.\n","title":"Vertical And Horizontal Privilege Escalation","type":"articles"},{"content":"If you need to create some Fake MVC objects for testing MVC objects then here you are:\nFakeControllerContext using System.Collections.Specialized; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.SessionState; using MvcContrib.TestHelper.Fakes;\npublic class FakeControllerContext : ControllerContext { public FakeControllerContext(IController controller) : this(controller, null, null, null, null, null, null) { }\npublic FakeControllerContext(IController controller, HttpCookieCollection cookies) : this(controller, null, null, null, null, cookies, null) { } public FakeControllerContext(IController controller, SessionStateItemCollection sessionItems) : this(controller, null, null, null, null, null, sessionItems) { } public FakeControllerContext(IController controller, NameValueCollection formParams) : this(controller, null, null, formParams, null, null, null) { } public FakeControllerContext(IController controller, NameValueCollection formParams, NameValueCollection queryStringParams) : this(controller, null, null, formParams, queryStringParams, null, null) { } public FakeControllerContext(IController controller, string userName) : this(controller, userName, null, null, null, null, null) { } public FakeControllerContext(IController controller, string userName, string[] roles) : this(controller, userName, roles, null, null, null, null) { } public FakeControllerContext ( IController controller, string userName, string[] roles, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems ) : base(new FakeHttpContext(new FakePrincipal(new FakeIdentity(userName), roles), formParams, queryStringParams, cookies, sessionItems), new RouteData(), (Controller)controller) { } }\nFakeHttpContext using System; using System.Collections.Specialized; using System.Security.Principal; using System.Web; using System.Web.SessionState; public class FakeHttpContext : HttpContextBase { private readonly FakePrincipal principal; private readonly NameValueCollection formParams; private readonly NameValueCollection queryStringParams; private readonly HttpCookieCollection cookies; private readonly SessionStateItemCollection sessionItems;\npublic FakeHttpContext(FakePrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems) { this.principal = principal; this.formParams = formParams; this.queryStringParams = queryStringParams; this.cookies = cookies; this.sessionItems = sessionItems; } public override HttpRequestBase Request { get { return new FakeHttpRequest(this.formParams, this.queryStringParams, this.cookies); } } public override IPrincipal User { get { return this.principal; } set { throw new NotImplementedException(); } } public override HttpSessionStateBase Session { get { return this.sessionItems == null ? null : new FakeHttpSessionState(this.sessionItems); } } }\nFakeHttpRequest using System.Collections.Specialized; using System.Web; public class FakeHttpRequest : HttpRequestBase { private readonly NameValueCollection formParams; private readonly NameValueCollection queryStringParams; private readonly HttpCookieCollection cookies;\npublic FakeHttpRequest(NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies) { this.formParams = formParams; this.queryStringParams = queryStringParams; this.cookies = cookies; } public override NameValueCollection Form { get { return this.formParams; } } public override NameValueCollection QueryString { get { return this.queryStringParams; } } public override HttpCookieCollection Cookies { get { return this.cookies; } } }\nFakeHttpSessionState using System.Collections; using System.Collections.Specialized; using System.Web; using System.Web.SessionState; public class FakeHttpSessionState : HttpSessionStateBase { private readonly SessionStateItemCollection sessionItems;\npublic FakeHttpSessionState(SessionStateItemCollection sessionItems) { this.sessionItems = sessionItems; } public override void Add(string name, object value) { this.sessionItems[name] = value; } public override int Count { get { return this.sessionItems.Count; } } public override IEnumerator GetEnumerator() { return this.sessionItems.GetEnumerator(); } public override NameObjectCollectionBase.KeysCollection Keys { get { return this.sessionItems.Keys; } } public override object this[string name] { get { return this.sessionItems[name]; } set { this.sessionItems[name] = value; } } public override object this[int index] { get { return this.sessionItems[index]; } set { this.sessionItems[index] = value; } } public override void Remove(string name) { this.sessionItems.Remove(name); } }\nFakePrincipal using System.Linq; using System.Security.Principal; public class FakePrincipal : IPrincipal { private readonly IIdentity identity; private readonly string[] roles;\npublic FakePrincipal(IIdentity identity, string[] roles) { this.identity = identity; this.roles = roles; } public IIdentity Identity { get { return this.identity; } } public bool IsInRole(string role) { return this.roles != null \u0026amp;amp;\u0026amp;amp; this.roles.Contains(role); } }\nThe original article and source is from Stephen Walter Faking the Controller Context\n","date":"19 December 2013","externalUrl":null,"permalink":"/make-fake-mvc-objects-for-testing/","section":"Articles","summary":"If you need to create some Fake MVC objects for testing MVC objects then here you are:\nFakeControllerContext using System.Collections.Specialized; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.SessionState; using MvcContrib.TestHelper.Fakes;\npublic class FakeControllerContext : ControllerContext { public FakeControllerContext(IController controller) : this(controller, null, null, null, null, null, null) { }\npublic FakeControllerContext(IController controller, HttpCookieCollection cookies) : this(controller, null, null, null, null, cookies, null) { } public FakeControllerContext(IController controller, SessionStateItemCollection sessionItems) : this(controller, null, null, null, null, null, sessionItems) { } public FakeControllerContext(IController controller, NameValueCollection formParams) : this(controller, null, null, formParams, null, null, null) { } public FakeControllerContext(IController controller, NameValueCollection formParams, NameValueCollection queryStringParams) : this(controller, null, null, formParams, queryStringParams, null, null) { } public FakeControllerContext(IController controller, string userName) : this(controller, userName, null, null, null, null, null) { } public FakeControllerContext(IController controller, string userName, string[] roles) : this(controller, userName, roles, null, null, null, null) { } public FakeControllerContext ( IController controller, string userName, string[] roles, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems ) : base(new FakeHttpContext(new FakePrincipal(new FakeIdentity(userName), roles), formParams, queryStringParams, cookies, sessionItems), new RouteData(), (Controller)controller) { } }","title":"Make Fake MVC Objects for testing","type":"articles"},{"content":"If you ever need a disclaimer page in MVC, there are a few things you need to consider, the first is you should not be able to get to a page without agreeing to the disclaimer and if you have to re-login then you need to be presented with the disclaimer page again.\nI’ve opted to use an Attribute, which can be used on a Controller.\n[AgreeToDisclaimer] public class Page1Controller : Controller { This makes things very simple and as easy to use as the Authorise Attribute.\nThe implementation of the AgreeToDisclaimer inherits the Authorize Attribute, which over rides the AuthorizeCore and HandleUnauthorizedRequest methods\npublic class AgreeToDisclaimerAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) throw new ArgumentNullException(\"httpContext\"); if (!this.HasAgreedToDisclaimer(httpContext)) return false; return true; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { // Returns HTTP 401 by default filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary { { \u0026quot;action\u0026quot;, \u0026quot;index\u0026quot; }, { \u0026quot;controller\u0026quot;, \u0026quot;Disclaimer\u0026quot; } }); } private bool HasAgreedToDisclaimer(HttpContextBase current) { return current != null \u0026amp;amp;\u0026amp;amp; current.User != null ? (bool)current.User.Disclaimer() : false; } }\nYou’ll have noticed that I have extended the User object to include Disclaimer, this way when the user session expires or the user logs out the current user is null\nAs for extending the User object this again is quite simple:\npublic static class IPrincipalExtension { /// \u0026lt;summary\u0026gt; /// ObjectCache references the objects with WeakReferences for avoiding memory leaks. /// \u0026lt;/summary\u0026gt; public static ConditionalWeakTable\u0026lt;object, Dictionary\u0026lt;string, object\u0026gt;\u0026gt; ObjectCache = new ConditionalWeakTable\u0026lt;object, Dictionary\u0026lt;string, object\u0026gt;\u0026gt;(); public static void SetValue\u0026amp;lt;T\u0026amp;gt;(this T obj, string name, object value) where T : class { Dictionary\u0026amp;lt;string, object\u0026amp;gt; properties = ObjectCache.GetOrCreateValue(obj); if (properties.ContainsKey(name)) properties[name] = value; else properties.Add(name, value); } public static T GetValue\u0026amp;lt;T\u0026amp;gt;(this object obj, object name) { Dictionary\u0026amp;lt;string, object\u0026amp;gt; properties; if (ObjectCache.TryGetValue(obj, out properties) \u0026amp;amp;\u0026amp;amp; properties.ContainsKey(name.ToString())) return (T)properties[name.ToString()]; else return default(T); } public static object GetValue(this object obj, bool name) { return obj.GetValue\u0026amp;lt;object\u0026amp;gt;(name); } public static bool Disclaimer(this IPrincipal principal) { return principal.GetValue\u0026amp;lt;bool\u0026amp;gt;(\u0026quot;Disclaimer\u0026quot;); } public static void SetDisclaimer(this IPrincipal principal, bool value) { principal.SetValue(\u0026quot;Disclaimer\u0026quot;, value); } }\n","date":"18 December 2013","externalUrl":null,"permalink":"/disclaimer-page-using-mvc/","section":"Articles","summary":"If you ever need a disclaimer page in MVC, there are a few things you need to consider, the first is you should not be able to get to a page without agreeing to the disclaimer and if you have to re-login then you need to be presented with the disclaimer page again.\n","title":"Disclaimer Page using MVC","type":"articles"},{"content":"Is the only difference between Debug and Release configurations that Debug have the DEBUG constant defined, and Release produces the Optimize code?\nAre there performance differences between these two configurations. Are there any specific type of code that will cause big differences in performance here, or is it actually not that important? Are there any type of code that will run fine under the Debug configuration that might fail under Release configuration, or can you be certain that code that is tested and working fine under the Debug configuration will also work fine under Release configuration. The C# compiler itself doesn’t alter the emitted IL a great deal in the Release build. Notable is that it no longer emits the NOP opcodes that allow you to set a breakpoint on a curly brace. The big one is the optimizer that’s built into the JIT compiler. It does make the following optimizations:\nMethod inlining. A method call is replaced by the injecting the code of the method. This is a big one, it makes property accessors essentially free. CPU register allocation. Local variables and method arguments can stay stored in a CPU register without ever (or less frequently) being stored back to the stack frame. This is a big one, notable for making debugging optimized code so difficult. And giving the volatile keyword a meaning. Array index checking elimination. An important optimization when working with arrays (all .NET collection classes use an array internally). When the JIT compiler can verify that a loop never indexes an array out of bounds then it will eliminate the index check. Big one. Loop unrolling. Short loops (up to 4) with small bodies are eliminated by repeating the code in the loop body. Avoids the branch misprediction penalty. Dead code elimination. A statement like if (false) { /…/ } gets completely eliminated. This can occur due to constant folding and inlining. Other cases is where the JIT compiler can determine that the code has no possible side-effect. This optimization is what makes profiling code so tricky. Code hoisting. Code inside a loop that is not affected by the loop can be moved out of the loop. Common sub-expression elimination. x = y + 4; z = y + 4; becomes z = x; Constant folding. x = 1 + 2; becomes x = 3; This simple example is caught early by the compiler, but happens at JIT time when other optimizations make this possible. Copy propagation. x = a; y = x; becomes y = a; This helps the register allocator make better decisions. It is a big deal in the x86 jitter because it has so few registers to work with. Having it select the right ones is critical to perf. These are very important optimizations that can make a great deal of difference when, for example, you profile the Debug build of your app and compare it to the Release build. That only really matters though when the code is on your critical path, the 5 to 10% of the code you write that actually affects the perf of your program. The JIT optimizer isn’t smart enough to know up front what is critical, it can only apply the “turn it to eleven” dial for all the code.\nThe effective result of these optimizations on your program’s execution time is often affected by code that runs elsewhere. Reading a file, executing a dbase query, etc. Making the work the JIT optimizer does completely invisible. It doesn’t mind though 🙂\nThe JIT optimizer is pretty reliable code, mostly because it has been put to the test millions of times. It is extremely rare to have problems in the Release build version of your program. It does happen however. Both the x64 and the x86 jitters have had problems with structs. The x86 jitter has trouble with floating point consistency, producing subtly different results when the intermediates of a floating point calculation are kept in a FPU register at 80-bit precision instead of getting truncated when flushed to memory.\nReference\n","date":"17 December 2013","externalUrl":null,"permalink":"/what-is-the-difference-between-running-in-debug-and-release-mode/","section":"Articles","summary":"Is the only difference between Debug and Release configurations that Debug have the DEBUG constant defined, and Release produces the Optimize code?\nAre there performance differences between these two configurations. Are there any specific type of code that will cause big differences in performance here, or is it actually not that important? Are there any type of code that will run fine under the Debug configuration that might fail under Release configuration, or can you be certain that code that is tested and working fine under the Debug configuration will also work fine under Release configuration. The C# compiler itself doesn’t alter the emitted IL a great deal in the Release build. Notable is that it no longer emits the NOP opcodes that allow you to set a breakpoint on a curly brace. The big one is the optimizer that’s built into the JIT compiler. It does make the following optimizations:\n","title":"What is the difference between running in Debug and Release mode?","type":"articles"},{"content":"With Visual Studio keep changing the way you create unit tests I thought I’d document down how to test a private method the easy way.\nHere is a simple HomeController and we want to test that the GetPageSize method return 20 in a unit test.\npublic class HomeController : Controller { public ActionResult Index() { var pageSize = GetPageSize(); return View(pageSize); } private int GetPageSize() { return 20; } }\nAs GetPageSize is a private method we’ll need to use the PrivateObject class to return the methods result, this is quite easy, from the Unit Test project make sure you have a reference to your MVC project and then reference the HomeController and invoke the method you need the result back from:\n[TestMethod] public void CheckPageSizeIs20() { PrivateObject privateObject = new PrivateObject(typeof(HomeController)); int pageSize; pageSize = (int)privateObject.Invoke(\"GetPageSize\"); Assert.AreEqual(20, pageSize); }\nIf you need to pass in parameters to the private method then you can pass in an anonymous type\nvar actual = (IEnumerable\u0026lt;ActivityData\u0026gt;)privateObject.Invoke(\"GetAllUnassignedJobs\", new object[] { filterData, uniqueJobs }); Reference: How to test a class member that is not public\nThanks to Karthik for googleing the answer\n","date":"17 December 2013","externalUrl":null,"permalink":"/unit-testing-a-private-method/","section":"Articles","summary":"With Visual Studio keep changing the way you create unit tests I thought I’d document down how to test a private method the easy way.\nHere is a simple HomeController and we want to test that the GetPageSize method return 20 in a unit test.\n","title":"Unit Testing a Private Method","type":"articles"},{"content":"Automation Fesability.docx (259.00 kb)\nAutomation tools and estimation.docx (16.94 kb)\nEXCEL- SHEET for estimation.xlsx (21.06 kb)\n","date":"17 December 2013","externalUrl":null,"permalink":"/automation-testing/","section":"Articles","summary":"Automation Fesability.docx (259.00 kb)\nAutomation tools and estimation.docx (16.94 kb)\nEXCEL- SHEET for estimation.xlsx (21.06 kb)\n","title":"Automation Testing","type":"articles"},{"content":"Hisenbugs\nHard to test concurrency, useally have test over a 5 week period and when you find the issues it is hard to reproduce\nLots of threads, and the behaviour of the program changes state and the interleaving changes and therefore it becomes hard to reproduce the concurrency issue, this is hope based testing, running on n number of machines and hope that we find a concurrency bug. This is not only costly, in having the ability to run all the processes on multiple machines, the resource involved in managing the logistics for running all the tests and more importantly if you find a concurrency issue can you reproduce the bug.\nSo what we need is to be able to control the interleaving of the programme, we need to be able to run again and again in a loop, and record the interleaving and then if we find a bug having the ability to repeat that test and interleaving to reproduce that bug\nCHESS is a tool for systematic and disciplined concurrency testing. Given a concurrent test, CHESS systematically enumerates the possible thread schedules to find hard-to-find concurrency errors, including assertion violations, deadlocks, data-races, and atomicity violations.\nhttp://msdn.microsoft.com/en-us/library/ms182480%28v=vs.90%29/\nTools And Techniques To Identify Concurrency Issues\nhttp://msdn.microsoft.com/en-us/magazine/cc546569/\nhanselminutes_0136.pdf (94.14 kb)\n","date":"13 December 2013","externalUrl":null,"permalink":"/concurrency/","section":"Articles","summary":"Hisenbugs\nHard to test concurrency, useally have test over a 5 week period and when you find the issues it is hard to reproduce\nLots of threads, and the behaviour of the program changes state and the interleaving changes and therefore it becomes hard to reproduce the concurrency issue, this is hope based testing, running on n number of machines and hope that we find a concurrency bug. This is not only costly, in having the ability to run all the processes on multiple machines, the resource involved in managing the logistics for running all the tests and more importantly if you find a concurrency issue can you reproduce the bug.\n","title":"Concurrency","type":"articles"},{"content":"","date":"13 December 2013","externalUrl":null,"permalink":"/categories/concurrency/","section":"Categories","summary":"","title":"Concurrency","type":"categories"},{"content":"Tasks in Migration Migrate users and login ID’s Map data types Map database objects: tables, triggers, views, stored procedures Update incompatible objects to work with SQL Azure Update application to work with SQL Azure Migrate data to SQL Azure ","date":"4 December 2013","externalUrl":null,"permalink":"/migration-from-sql-to-sql-azure/","section":"Articles","summary":"Tasks in Migration Migrate users and login ID’s Map data types Map database objects: tables, triggers, views, stored procedures Update incompatible objects to work with SQL Azure Update application to work with SQL Azure Migrate data to SQL Azure ","title":"Migration from SQL to SQL Azure","type":"articles"},{"content":"Not my fix, but it works\n@ECHO OFF :IE10HACK REG ADD \u0026ldquo;HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\u0026rdquo; /v Version /t REG_SZ /d \u0026ldquo;9.10.9200.16384\u0026rdquo; /f REG ADD \u0026ldquo;HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\u0026rdquo; /v svcVersion /t REG_SZ /d \u0026ldquo;10.0.9200.16384\u0026rdquo; /f REG ADD \u0026ldquo;HKLM\\SOFTWARE\\Microsoft\\Internet Explorer\u0026rdquo; /v Version /t REG_SZ /d \u0026ldquo;9.10.9200.16384\u0026rdquo; /f REG ADD \u0026ldquo;HKLM\\SOFTWARE\\Microsoft\\Internet Explorer\u0026rdquo; /v svcVersion /t REG_SZ /d \u0026ldquo;10.0.9200.16384\u0026rdquo; /f GOTO EXIT\n:REVERTIE REG DELETE \u0026ldquo;HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\u0026rdquo; /v svcVersion REG DELETE \u0026ldquo;HKLM\\SOFTWARE\\Microsoft\\Internet Explorer\u0026rdquo; /v svcVersion REG ADD \u0026ldquo;HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\u0026rdquo; /v Version /t REG_SZ /d \u0026ldquo;8.0.7601.17514\u0026rdquo; /f REG ADD \u0026ldquo;HKLM\\SOFTWARE\\Microsoft\\Internet Explorer\u0026rdquo; /v Version /t REG_SZ /d \u0026ldquo;8.0.7601.17514\u0026rdquo; /f GOTO EXIT\n:EXIT\ncredit goses to Jimmy http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/4153040-remove-the-requirment-for-internet-explorer-10-to-\n","date":"31 October 2013","externalUrl":null,"permalink":"/visual-studio-2013-requires-internet-explorer-10-how-to-install-without-ie10/","section":"Articles","summary":"Not my fix, but it works\n@ECHO OFF :IE10HACK REG ADD “HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer” /v Version /t REG_SZ /d “9.10.9200.16384” /f REG ADD “HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer” /v svcVersion /t REG_SZ /d “10.0.9200.16384” /f REG ADD “HKLM\\SOFTWARE\\Microsoft\\Internet Explorer” /v Version /t REG_SZ /d “9.10.9200.16384” /f REG ADD “HKLM\\SOFTWARE\\Microsoft\\Internet Explorer” /v svcVersion /t REG_SZ /d “10.0.9200.16384” /f GOTO EXIT\n:REVERTIE REG DELETE “HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer” /v svcVersion REG DELETE “HKLM\\SOFTWARE\\Microsoft\\Internet Explorer” /v svcVersion REG ADD “HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer” /v Version /t REG_SZ /d “8.0.7601.17514” /f REG ADD “HKLM\\SOFTWARE\\Microsoft\\Internet Explorer” /v Version /t REG_SZ /d “8.0.7601.17514” /f GOTO EXIT\n:EXIT","title":"Visual Studio 2013 requires Internet Explorer 10 – how to install without IE10","type":"articles"},{"content":"No web applications are developed without concerning the security issues. But it is not sure whether the security measures are implemented correctly and the applications are well protected. We could see a lot of web applications query string parameters in plain string which are easy to manipulate and way to escalate restricted resources. Even the URL parameters are encrypted there is still a chance of a bruteforce attack by manipulating the encrypted hash and it yields when the database is large where the chance of matching a random hash is high. So it is clear the importance to protect the URL in the web application is necessary for all programming platforms. Here, this is discussed with reference to ASP.NET MVC and the utility class is presented.\n.NET Framework has a lot of improved methods for security and the MVC framework introduced new security methods like AntiForgeryToken that I discussed in a previous article Preventing Cross Site Request Forgery. Let us have a brief look at the security methods in general practice.\nAuthorize attribute: This is useful to authorize a user or role to access any resource in the application after authenticated. This helps to have User and Role level protections. Http Referrer Check: This is a general method not confined to .NET. This is to prevent an URL request which is not from the site, but from an external link or the link directly executed at the browser navigation Anti Forgery Token: This is a powerful option to prevent any hidden field manipulation while form posting and prevents Cross-Site Request Forgery HTML Encoding: It is advised to encode all user inputs to prevent Cross Site Scripting attack/ XSS attack etc., Protection against SQL injections Encryption of Query string parameters. This is good way to prevent manipulation of query string parameters. But this is not a complete protection, still vulnerable for a brute force attack. Even though all the above methods are available, .NET framework doesn’t provide an inbuilt functionality for protecting the URL parameters. Its URL authorization technique protects the whole URL, but not parts of the URL which are still vulnerable for manipulation. This piece of coding here helps to easily implement all these security methods with special importance to protecting the URL parameters. Creating a URL hash is not new but yet it is not a common practice in the industry though it is an important concern. So it would be important to share a piece of code for the easy implementation of this method in ASP.NET MVC.\nThe basic idea is simple, encrypting the URL parameters along with controller, action names to a hash and later it will be passed to server as a URL parameter. The hash will be verified at the server side for its validity by recomputing the hash and compared with the submitted hash. This hash is dynamic and specific to a session. So even though your URL cached in the man-in-the middle attack, it will not work in other sessions. Basically a utility class extends the HTML helper ActionLink class. So we can use Html.ActionLink method as such in the MVC implementation, in addition you only need to pass a boolean argument as a last argument to get the protected URL. It is pretty easy to use this coding. Examples are shown below.\n\u0026lt;%=Html.ActionLink(\"link Test 3\", \"HandleLink\", new { id = 200 }, true)%\u0026gt; You’ll notice the extra boolean parameter at the end to enable encryption.\nThe ExtendedHtmlActionLinkHelper looks like this:\nnamespace ExtendedHtmlActionLinkHelper { using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using System.Web.Routing; /// \u0026amp;lt;summary\u0026amp;gt; /// This class is an extension for the Html Helper /// \u0026amp;lt;/summary\u0026amp;gt; public static class ActionLinkExtensions { // This password is included in the hash. If needed it can be changed. private static string tokenPassword = \u0026quot;@#123%#\u0026quot;; public static string TokenPassword { get { return tokenPassword; } set { tokenPassword = value; } } /// \u0026amp;lt;summary\u0026amp;gt; /// This is the extended method of Html.ActionLink.This class has the extended methods for the 10 overloads of this method /// All the overloaded method applys the same logic excepts the parameters passed in /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;helper\u0026quot;\u0026amp;gt;The helper.\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;linkText\u0026quot;\u0026amp;gt;The link text.\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;actionName\u0026quot;\u0026amp;gt;Name of the action.\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;generateToken\u0026quot;\u0026amp;gt;if set to \u0026amp;lt;c\u0026amp;gt;true\u0026amp;lt;/c\u0026amp;gt; [generate token].\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; public static MvcHtmlString ActionLink(this HtmlHelper helper, string linkText, string actionName, bool generateToken) { var rc = helper.ViewContext.RequestContext; var routeCollection = helper.RouteCollection; var rvd = new RouteValueDictionary(); if (generateToken) { // Call the generateUrlToken method which create the hash var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd, TokenPassword); // The hash is added to the route value dictionary rvd.Add(\u0026quot;urltoken\u0026quot;, token); } // the link is formed by using the GenerateLink method. var link = HtmlHelper.GenerateLink(rc, routeCollection, linkText, null, actionName, null, rvd, null); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString ActionLink(this HtmlHelper helper, string linkText, string actionName, object routeValues, bool generateToken) { var rc = helper.ViewContext.RequestContext; var routeCollection = helper.RouteCollection; var rvd = new RouteValueDictionary(routeValues); if (generateToken) { var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd, TokenPassword); rvd.Add(\u0026quot;urltoken\u0026quot;, token); } var link = HtmlHelper.GenerateLink(rc, routeCollection, linkText, null, actionName, null, rvd, null); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString ActionLink(this HtmlHelper helper, string linkText, string actionName, RouteValueDictionary routeValues, bool generateToken) { var rc = helper.ViewContext.RequestContext; var routeCollection = helper.RouteCollection; var rvd = routeValues; if (generateToken) { var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd, TokenPassword); rvd.Add(\u0026quot;urltoken\u0026quot;, token); } var link = HtmlHelper.GenerateLink(rc, routeCollection, linkText, null, actionName, null, rvd, null); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString ActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName, bool generateToken) { var rc = helper.ViewContext.RequestContext; var routeCollection = helper.RouteCollection; var rvd = new RouteValueDictionary(); if (generateToken) { var token = TokenUtility.GenerateUrlToken(controllerName, actionName, rvd, TokenPassword); rvd.Add(\u0026quot;urltoken\u0026quot;, token); } var link = HtmlHelper.GenerateLink(rc, routeCollection, linkText, null, actionName, controllerName, rvd, null); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString ActionLink(this HtmlHelper helper, string linkText, string actionName, object routeValues, object htmlAttributes, bool generateToken) { var rc = helper.ViewContext.RequestContext; var routeCollection = helper.RouteCollection; var rvd = new RouteValueDictionary(routeValues); if (generateToken) { var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd, TokenPassword); rvd.Add(\u0026quot;urltoken\u0026quot;, token); } var attrib = GetDictionaryFromObject(htmlAttributes); var link = HtmlHelper.GenerateLink(rc, routeCollection, linkText, null, actionName, null, rvd, attrib); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString ActionLink(this HtmlHelper helper, string linkText, string actionName, RouteValueDictionary routeValues, IDictionary\u0026amp;lt;string, object\u0026amp;gt; htmlAttributes, bool generateToken) { var rc = helper.ViewContext.RequestContext; var routeCollection = helper.RouteCollection; if (generateToken) { var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, routeValues, TokenPassword); routeValues.Add(\u0026quot;urltoken\u0026quot;, token); } var link = HtmlHelper.GenerateLink(rc, routeCollection, linkText, null, actionName, null, routeValues, htmlAttributes); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString ActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes, bool generateToken) { var rc = helper.ViewContext.RequestContext; var routeCollection = helper.RouteCollection; var rvd = new RouteValueDictionary(routeValues); if (generateToken) { var token = TokenUtility.GenerateUrlToken(controllerName, actionName, rvd, TokenPassword); rvd.Add(\u0026quot;urltoken\u0026quot;, token); } var attrib = GetDictionaryFromObject(htmlAttributes); var link = HtmlHelper.GenerateLink(rc, routeCollection, linkText, null, actionName, controllerName, rvd, attrib); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString ActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary\u0026amp;lt;string, object\u0026amp;gt; htmlAttributes, bool generateToken) { var rc = helper.ViewContext.RequestContext; var routeCollection = helper.RouteCollection; if (generateToken) { var token = TokenUtility.GenerateUrlToken(controllerName, actionName, routeValues, TokenPassword); routeValues.Add(\u0026quot;urltoken\u0026quot;, token); } var link = HtmlHelper.GenerateLink(rc, routeCollection, linkText, null, actionName, controllerName, routeValues, htmlAttributes); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString ActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, object routeValues, object htmlAttributes, bool generateToken) { var rc = helper.ViewContext.RequestContext; var routeCollection = helper.RouteCollection; var rvd = new RouteValueDictionary(routeValues); if (generateToken) { var token = TokenUtility.GenerateUrlToken(controllerName, actionName, rvd, TokenPassword); rvd.Add(\u0026quot;urltoken\u0026quot;, token); } var attrib = GetDictionaryFromObject(htmlAttributes); var link = HtmlHelper.GenerateLink(rc, routeCollection, linkText, null, actionName, controllerName, protocol, hostName, fragment, rvd, attrib); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString ActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary\u0026amp;lt;string, object\u0026amp;gt; htmlAttributes, bool generateToken) { var rc = helper.ViewContext.RequestContext; var routeCollection = helper.RouteCollection; if (generateToken) { var token = TokenUtility.GenerateUrlToken(controllerName, actionName, routeValues, TokenPassword); routeValues.Add(\u0026quot;urltoken\u0026quot;, token); } var link = HtmlHelper.GenerateLink(rc, routeCollection, linkText, null, actionName, controllerName, protocol, hostName, fragment, routeValues, htmlAttributes); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } private static IDictionary\u0026amp;lt;string, object\u0026amp;gt; GetDictionaryFromObject(object sourceObject) { var objType = sourceObject.GetType(); return objType.GetProperties().ToDictionary(prop =\u0026amp;gt; prop.Name, prop =\u0026amp;gt; prop.GetValue(sourceObject, null)); } } }\nIt is also worth generating the UrlHelper.Action too should this be required\nusing System.Web.Mvc; using System.Web.Routing; public static class ActionExtensions { public static MvcHtmlString Action(this UrlHelper helper, string actionName, bool generateToken) { var rvd = new RouteValueDictionary(); if (generateToken) { // Call the generateUrlToken method which create the hash var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd);\n// The hash is added to the route value dictionary rvd.Add(\u0026quot;urltoken\u0026quot;, token); } // the link is formed by using the GenerateLink method. var link = new UrlHelper(helper.RequestContext).Action(actionName, rvd); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString Action(this UrlHelper helper, string actionName, object routeValues, bool generateToken) { if(routeValues== null) { routeValues = new RouteValueDictionary(); } var rvd = (RouteValueDictionary)routeValues; if (generateToken) { // Call the generateUrlToken method which create the hash var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd); // The hash is added to the route value dictionary rvd.Add(\u0026quot;urltoken\u0026quot;, token); } // the link is formed by using the GenerateLink method. var link = new UrlHelper(helper.RequestContext).Action(actionName, rvd); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString Action(this UrlHelper helper, string actionName, RouteValueDictionary routeValues, bool generateToken) { if (routeValues == null) { routeValues = new RouteValueDictionary(); } var rvd = routeValues; if (generateToken) { // Call the generateUrlToken method which create the hash var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd); // The hash is added to the route value dictionary rvd.Add(\u0026quot;urltoken\u0026quot;, token); } // the link is formed by using the GenerateLink method. var link = new UrlHelper(helper.RequestContext).Action(actionName, rvd); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString Action(this UrlHelper helper, string actionName, string controllerName, bool generateToken) { var rvd = new RouteValueDictionary(); if (generateToken) { // Call the generateUrlToken method which create the hash var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd); // The hash is added to the route value dictionary rvd.Add(\u0026quot;urltoken\u0026quot;, token); } // the link is formed by using the GenerateLink method. var link = new UrlHelper(helper.RequestContext).Action(actionName, controllerName, rvd); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString Action(this UrlHelper helper, string actionName, string controllerName, object routeValues, bool generateToken) { if (routeValues == null) { routeValues = new RouteValueDictionary(); } var rvd = (RouteValueDictionary)routeValues; if (generateToken) { // Call the generateUrlToken method which create the hash var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd); // The hash is added to the route value dictionary rvd.Add(\u0026quot;urltoken\u0026quot;, token); } // the link is formed by using the GenerateLink method. var link = new UrlHelper(helper.RequestContext).Action(actionName, controllerName, rvd); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString Action(this UrlHelper helper, string actionName, string controllerName, RouteValueDictionary routeValues, bool generateToken) { if (routeValues == null) { routeValues = new RouteValueDictionary(); } var rvd = routeValues; if (generateToken) { // Call the generateUrlToken method which create the hash var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd); // The hash is added to the route value dictionary rvd.Add(\u0026quot;urltoken\u0026quot;, token); } // the link is formed by using the GenerateLink method. var link = new UrlHelper(helper.RequestContext).Action(actionName, controllerName, rvd); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString Action(this UrlHelper helper, string actionName, string controllerName, object routeValues, string protocol, bool generateToken) { if (routeValues == null) { routeValues = new RouteValueDictionary(); } var rvd = (RouteValueDictionary)routeValues; if (generateToken) { // Call the generateUrlToken method which create the hash var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd); // The hash is added to the route value dictionary rvd.Add(\u0026quot;urltoken\u0026quot;, token); } // the link is formed by using the GenerateLink method. var link = new UrlHelper(helper.RequestContext).Action(actionName, controllerName, rvd, protocol); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } public static MvcHtmlString Action(this UrlHelper helper, string actionName, string controllerName, RouteValueDictionary routeValues, string protocol, string hostName, bool generateToken) { if (routeValues == null) { routeValues = new RouteValueDictionary(); } var rvd = routeValues; if (generateToken) { // Call the generateUrlToken method which create the hash var token = TokenUtility.GenerateUrlToken(string.Empty, actionName, rvd); // The hash is added to the route value dictionary rvd.Add(\u0026quot;urltoken\u0026quot;, token); } // the link is formed by using the GenerateLink method. var link = new UrlHelper(helper.RequestContext).Action(actionName, controllerName, rvd, protocol, hostName); var mvcHtmlString = MvcHtmlString.Create(link); return mvcHtmlString; } }Getting a protected URL in the view is easy as just passing a boolean parameter. Now let us see how to validate the URL when submitted to controller. It is even simpler. Just add this attribute to the controller method.\n[IsValidURLRequest] This attribute has taken care of the simple authorize check (user name, password verification), check for http referrer and protect the URL parameters.\nNow for the TokenUtility that performs most of the work for creating the URL Hash.\nusing System; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Web; using System.Web.Routing; /// \u0026lt;summary\u0026gt; /// This is a static helper class which creates the URL Hash /// \u0026lt;/summary\u0026gt; public static class TokenUtility { public static string GenerateUrlToken(string controllerName, string actionName, RouteValueDictionary argumentParams, string password) { //// The URL hash is dynamic by assign a dynamic key in each session. So //// eventhough your URL is stolen, it will not work in other session if (HttpContext.Current.Session[\u0026ldquo;url_dynamickey\u0026rdquo;] == null) { HttpContext.Current.Session[\u0026ldquo;url_dynamickey\u0026rdquo;] = RandomString(); }\n// The salt include the dynamic session key and valid for an hour. var salt = HttpContext.Current.Session[\u0026quot;url_dynamickey\u0026quot;] + DateTime.Now.ToShortDateString() + \u0026quot; \u0026quot; + DateTime.Now.Hour; // generating the partial url var stringToToken = controllerName + \u0026quot;/\u0026quot; + actionName + \u0026quot;/\u0026quot;; stringToToken = argumentParams.Where(item =\u0026amp;gt; item.Key != \u0026quot;controller\u0026quot; \u0026amp;amp;\u0026amp;amp; item.Key != \u0026quot;action\u0026quot; \u0026amp;amp;\u0026amp;amp; item.Key != \u0026quot;urltoken\u0026quot;).Aggregate(stringToToken, (current, item) =\u0026amp;gt; current + (item.Value)); // Converting the salt in to a byte array var saltValueBytes = System.Text.Encoding.ASCII.GetBytes(salt); // Encrypt the salt bytes with the password var key = new Rfc2898DeriveBytes(password, saltValueBytes); // get the key bytes from the above process var secretKey = key.GetBytes(16); // generate the hash var tokenHash = new HMACSHA1(secretKey); tokenHash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(stringToToken)); // convert the hash to a base64string var token = Convert.ToBase64String(tokenHash.Hash).Replace(\u0026quot;/\u0026quot;, \u0026quot;_\u0026quot;); return token; } /// \u0026amp;lt;summary\u0026amp;gt; /// This validates the token /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;token\u0026quot;\u0026amp;gt;The token.\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;controllerName\u0026quot;\u0026amp;gt;Name of the controller.\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;actionName\u0026quot;\u0026amp;gt;Name of the action.\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;argumentParams\u0026quot;\u0026amp;gt;The argument params.\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;password\u0026quot;\u0026amp;gt;The password.\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; public static bool ValidateToken(string token, string controllerName, string actionName, RouteValueDictionary argumentParams, string password) { // compute the token for the currrent parameter var computedToken = GenerateUrlToken(controllerName, actionName, argumentParams, password); // compare with the submitted token if (computedToken != token) { computedToken = GenerateUrlToken(string.Empty, actionName, argumentParams, password); } else { return true; } return computedToken == token; } /// \u0026amp;lt;summary\u0026amp;gt; /// It validates the token, where all the parameters passed as a RouteValueDictionary /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;requestUrlParts\u0026quot;\u0026amp;gt;The request URL parts.\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;password\u0026quot;\u0026amp;gt;The password.\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;token\u0026quot;\u0026amp;gt;the Url encrypted token to be used to validate against\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; public static bool ValidateToken(RouteValueDictionary requestUrlParts, string password, string token) { // get the parameters string controllerName; try { controllerName = Convert.ToString(requestUrlParts[\u0026quot;controller\u0026quot;]); } catch (Exception) { controllerName = string.Empty; } var actionName = Convert.ToString(requestUrlParts[\u0026quot;action\u0026quot;]); //var token = Convert.ToString(requestUrlParts[\u0026quot;urltoken\u0026quot;]); // Compute a new hash var computedToken = GenerateUrlToken(controllerName, actionName, requestUrlParts, password); // compare with the submited hash if (computedToken != token) { computedToken = GenerateUrlToken(string.Empty, actionName, requestUrlParts, password); } else { return true; } return computedToken == token; } /// \u0026amp;lt;summary\u0026amp;gt; /// This method create the random dynamic key for the session /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; private static string RandomString() { var builder = new StringBuilder(); var random = new Random(); for (var i = 0; i \u0026amp;lt; 8; i++) { var ch = Convert.ToChar(Convert.ToInt32(Math.Floor((26 * random.NextDouble()) + 65))); builder.Append(ch); } return builder.ToString(); } }\nExtendedHtmlActionLinkHelper (3).zip (277.13 kb)\nOriginal Source\n","date":"30 October 2013","externalUrl":null,"permalink":"/url-activity-tampering-and-how-to-prevent-it-in-mvc/","section":"Articles","summary":"No web applications are developed without concerning the security issues. But it is not sure whether the security measures are implemented correctly and the applications are well protected. We could see a lot of web applications query string parameters in plain string which are easy to manipulate and way to escalate restricted resources. Even the URL parameters are encrypted there is still a chance of a bruteforce attack by manipulating the encrypted hash and it yields when the database is large where the chance of matching a random hash is high. So it is clear the importance to protect the URL in the web application is necessary for all programming platforms. Here, this is discussed with reference to ASP.NET MVC and the utility class is presented.\n","title":"URL Activity Tampering and how to prevent it in MVC","type":"articles"},{"content":"One of the issue we all faced with is when a user searches for content, we are allowing the end user to be able to search for anything and this could result in unnecessary searching or cause the backend to perform searches which could result in DOS attacks via SQL.\nI have covered DOS attacks via SQL before\nhttps://bryanavery.co.uk/post/2013/10/01/Denial-Of-Service-attacks-via-SQL-Wildcards-should-be-prevented/\nSQL Wildcard attacks force the underlying database to carry out CPU-intensive queries by using several wildcards. This vulnerability generally exists in search functionalities of web applications. Successful exploitation of this attack will cause Denial of Service.\nDepending on the connection pooling settings of the application and the time taken for attack query to execute, an attacker might be able to consume all connections in the connection pool, which will cause database queries to fail for legitimate users.\nBy default in ASP.NET, the maximum allowed connections in the pool is 100 and timeout is 30 seconds. Thus if an attacker can run 100 multiple queries with 30+ seconds execution time within 30 seconds no one else would be able to use the database related parts of the application.\nRecommendation: If the application does not require this sort of advanced search, all wildcards should be escaped or filtered. References:\nOWASP Testing for SQL Wildcard Attacks https://www.owasp.org/index.php/Testing_for_SQL_Wildcard_Attacks_(OWASP-DS-001) DoS Attacks using SQL Wildcards http://www.zdnet.com/blog/security/dos-attacks-using-sql-wildcards-revealed/1134\nSo I’ve went to work to produce a Sequence Diagram on what we need to do to Clean the Content\nI’ve generated this method for cleaning content which helps with removing unwanted characters\nusing System; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Text.RegularExpressions; public class Search { /// \u0026lt;summary\u0026gt; /// The regex strip html. /// \u0026lt;/summary\u0026gt; private readonly Regex RegexStripHtml = new Regex(\u0026quot;\u0026lt;[^\u0026gt;]*\u0026gt;\u0026quot;, RegexOptions.Compiled);\nprivate StringCollection StopWords { get { var stopWords = new StringCollection(); return stopWords; } } /// \u0026amp;lt;summary\u0026amp;gt; /// Removes stop words and HTML from the specified string. /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;content\u0026quot;\u0026amp;gt; /// The content. /// \u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;removeHtml\u0026quot;\u0026amp;gt; /// The remove Html. /// \u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;returns\u0026amp;gt; /// The clean content. /// \u0026amp;lt;/returns\u0026amp;gt; public string CleanContent(string content, bool removeHtml) { if (removeHtml) { content = this.StripHtml(content); } content = content.Replace(\u0026quot;\\\\\u0026quot;, string.Empty).Replace(\u0026quot;|\u0026quot;, string.Empty).Replace(\u0026quot;(\u0026quot;, string.Empty).Replace(\u0026quot;)\u0026quot;, string.Empty).Replace(\u0026quot;[\u0026quot;, string.Empty).Replace(\u0026quot;]\u0026quot;, string.Empty).Replace(\u0026quot;*\u0026quot;, string.Empty).Replace(\u0026quot;?\u0026quot;, string.Empty).Replace(\u0026quot;}\u0026quot;, string.Empty).Replace(\u0026quot;{\u0026quot;, string.Empty).Replace(\u0026quot;^\u0026quot;, string.Empty).Replace(\u0026quot;+\u0026quot;, string.Empty).Replace(\u0026quot;%\u0026quot;, string.Empty).Replace(\u0026quot;_\u0026quot;, string.Empty); var words = content.Split(new[] { ' ', '\\n', '\\r' }, StringSplitOptions.RemoveEmptyEntries); var sb = new StringBuilder(); foreach (var word in words.Select(t =\u0026amp;gt; t.ToLowerInvariant().Trim()).Where(word =\u0026amp;gt; RemoveSingleCharacters(word) \u0026amp;amp;\u0026amp;amp; RemoveStopWords(word))) { sb.AppendFormat(\u0026quot;{0} \u0026quot;, word); } return sb.ToString().Trim(); } /// \u0026amp;lt;summary\u0026amp;gt; /// Strips all HTML tags from the specified string. /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;html\u0026quot;\u0026amp;gt; /// The string containing HTML /// \u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;returns\u0026amp;gt; /// A string without HTML tags /// \u0026amp;lt;/returns\u0026amp;gt; public string StripHtml(string html) { return this.StringIsNullOrWhitespace(html) ? string.Empty : this.RegexStripHtml.Replace(html, string.Empty).Trim(); } /// \u0026amp;lt;summary\u0026amp;gt; /// Returns whether a string is null, empty, or whitespace. Same implementation as in String.IsNullOrWhitespace in .Net 4.0 /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;value\u0026quot;\u0026amp;gt;\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; public bool StringIsNullOrWhitespace(string value) { return value == null || value.Trim().Length == 0; } /// \u0026amp;lt;summary\u0026amp;gt; /// Removes the single characters. /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;word\u0026quot;\u0026amp;gt;The word.\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; private bool RemoveSingleCharacters(string word) { return word.Length \u0026amp;gt; 1; } /// \u0026amp;lt;summary\u0026amp;gt; /// Removes the stop words. /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;word\u0026quot;\u0026amp;gt;The word.\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; private bool RemoveStopWords(string word) { return !this.StopWords.Contains(word); } }\n","date":"28 October 2013","externalUrl":null,"permalink":"/clean-content-to-help-searching/","section":"Articles","summary":"One of the issue we all faced with is when a user searches for content, we are allowing the end user to be able to search for anything and this could result in unnecessary searching or cause the backend to perform searches which could result in DOS attacks via SQL.\n","title":"Clean Content to help searching","type":"articles"},{"content":"I needed to check to see if a URL that the user was entering was a valid Url, does it contain HTTP:// or HTTPS:// I ended up writing a small ValidationAttribute to add to the collection I am now building up, here is the code:\nusing System; using System.ComponentModel.DataAnnotations; using System.Net; public class IsUriAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var myString = value.ToString(); Uri myUri; if (Uri.TryCreate(myString, UriKind.Absolute, out myUri) \u0026amp;\u0026amp; (myUri.Scheme == Uri.UriSchemeHttp || myUri.Scheme == Uri.UriSchemeHttps)) { return ValidateUri(myUri); } return new ValidationResult(\u0026ldquo;URL is invalid.\\nStart with http:// or https:// and end with\\na proper image extension\u0026rdquo;); }\nprivate ValidationResult ValidateUri(Uri myUri) { var webRequest = WebRequest.Create(myUri); try { webRequest.GetResponse(); } catch //If exception thrown then couldn't get response from address { return new ValidationResult(\u0026quot;URL is invalid and does not exist\u0026quot;); } return ValidationResult.Success; } }\n","date":"25 October 2013","externalUrl":null,"permalink":"/url-validator/","section":"Articles","summary":"I needed to check to see if a URL that the user was entering was a valid Url, does it contain HTTP:// or HTTPS:// I ended up writing a small ValidationAttribute to add to the collection I am now building up, here is the code:\n","title":"URL Validator","type":"articles"},{"content":"I know the WebGrid is a basic Grid control, but sometimes you are constrained with what you can use with a customer and WebGrid is by default from Microsoft so it is safe to use and does not require any unknown third party tools to be installed.\nBy default the WebGrid requires all the data to be loaded in order for paging to work. The problem is when you page through the data, all the data is returned. If you try to limit the data being returned, the problem you’ll encounter because you’re only returning a subset of the data is the WebGrid thinks there’s only that amount of data to display, so the paging links will disappear! Not good! This is the reason why I’m writing this blog post to over come this issue.\nThroughout this example I’ve tried to keep to using interfaces where ever possible as I always think these are easier to understand and keep the application more flexible.\nThe WebGrid supports dynamic typing, while dynamic typing is probably a good fit for WebMatrix, there are benefits to strongly typed views. One way to achieve this is to create a derived type WebGrid\u0026lt;T\u0026gt;, here it is:\nusing System; using System.Collections.Generic; using System.Web.Helpers; public class WebGrid\u0026lt;T\u0026gt; : WebGrid { public WebGrid(IEnumerable\u0026lt;T\u0026gt; source = null, IEnumerable\u0026lt;string\u0026gt; columnNames = null, string defaultSort = null, int rowsPerPage = 10, bool canPage = true, bool canSort = true, string ajaxUpdateContainerId = null, string ajaxUpdateCallback = null, string fieldNamePrefix = null, string pageFieldName = null, string selectionFieldName = null, string sortFieldName = null, string sortDirectionFieldName = null) : base(source.SafeCast\u0026lt;object\u0026gt;(), columnNames, defaultSort, rowsPerPage, canPage, canSort, ajaxUpdateContainerId, ajaxUpdateCallback, fieldNamePrefix, pageFieldName, selectionFieldName, sortFieldName, sortDirectionFieldName) { } public WebGridColumn _Column(string columnName = null, string header = null, Func\u0026lt;T, object\u0026gt; format = null, string style = null, bool canSort = true) { Func\u0026lt;object, object\u0026gt; wrappedFormat = null; if (format != null) { wrappedFormat = o =\u0026gt; format((T)o); } var _scolumn = base.Column(columnName, header, wrappedFormat, style, canSort); return _scolumn; } public WebGrid\u0026lt;T\u0026gt; _Bind(IEnumerable\u0026lt;T\u0026gt; source, IEnumerable\u0026lt;string\u0026gt; columnNames = null, bool autoSortAndPage = true, int rowCount = -1) { base.Bind(source.SafeCast\u0026lt;object\u0026gt;(), columnNames, autoSortAndPage, rowCount); return this; } }\nAnd to extend the exisiting WebGrid we require a static extension:\nusing System.Web.Mvc; using System.Collections.Generic; public static class WebGridExtensions { public static WebGrid\u0026lt;T\u0026gt; Grid\u0026lt;T\u0026gt;(this HtmlHelper htmlHelper, IEnumerable\u0026lt;T\u0026gt; source, IEnumerable\u0026lt;string\u0026gt; columnNames = null, string defaultSort = null, int rowsPerPage = 10, bool canPage = true, bool canSort = true, string ajaxUpdateContainerId = null, string ajaxUpdateCallback = null, string fieldNamePrefix = null, string pageFieldName = null, string selectionFieldName = null, string sortFieldName = null, string sortDirectionFieldName = null) { return new WebGrid\u0026lt;T\u0026gt;(source, columnNames, defaultSort, rowsPerPage, canPage, canSort, ajaxUpdateContainerId, ajaxUpdateCallback, fieldNamePrefix, pageFieldName, selectionFieldName, sortFieldName, sortDirectionFieldName); }\npublic static WebGrid\u0026amp;lt;T\u0026amp;gt; ServerPagedGrid\u0026amp;lt;T\u0026amp;gt;(this HtmlHelper htmlHelper, IEnumerable\u0026amp;lt;T\u0026amp;gt; source, int totalRows, IEnumerable\u0026amp;lt;string\u0026amp;gt; columnNames = null, string defaultSort = null, int rowsPerPage = 10, bool canPage = true, bool canSort = true, string ajaxUpdateContainerId = null, string ajaxUpdateCallback = null, string fieldNamePrefix = null, string pageFieldName = null, string selectionFieldName = null, string sortFieldName = null, string sortDirectionFieldName = null) { dynamic webGrid = new WebGrid\u0026amp;lt;T\u0026amp;gt;(null, columnNames, defaultSort, rowsPerPage, canPage, canSort, ajaxUpdateContainerId, ajaxUpdateCallback, fieldNamePrefix, pageFieldName, selectionFieldName, sortFieldName, sortDirectionFieldName); return webGrid.Bind(source, rowCount: totalRows, autoSortAndPage: false); } }\nOne further method we will need is a SafeCast to extend the Enumerable\nusing System.Collections; using System.Collections.Generic; using System.Linq; public static class EnumerableExtensions { public static IEnumerable\u0026lt;TTarget\u0026gt; SafeCast\u0026lt;TTarget\u0026gt;(this IEnumerable source) { return source == null ? null : source.Cast\u0026lt;TTarget\u0026gt;(); } }\nOkay so this is it for the infrastructure, now lets get down to using the new WebGrid, so first the domain objects or interfaces we want to display\nusing System; public interface IDocument { global::System.Guid Id { get; set; } DateTime? Timestamp { get; set; } global::System.Boolean Inactive { get; set; } }\nNow for the important worker, the Service interface:\nusing System.Collections.Generic; public interface IDocumentService { IEnumerable\u0026lt;IDocument\u0026gt; GetDocuments(out int totalRecords, int pageSize = -1, int pageIndex = -1, string sort = \u0026ldquo;Id\u0026rdquo;, SortDirection sortOrder = SortDirection.Ascending); }\nand the impmentation looks something like this:\nusing System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; public class EfDocumentService : IDocumentService { private readonly IDictionary\u0026lt;string, Func\u0026lt;IQueryable\u0026lt;IDocument\u0026gt;, bool, IOrderedQueryable\u0026lt;IDocument\u0026gt;\u0026gt;\u0026gt; _documentOrderings = new Dictionary\u0026lt;string, Func\u0026lt;IQueryable\u0026lt;IDocument\u0026gt;, bool, IOrderedQueryable\u0026lt;IDocument\u0026gt;\u0026gt;\u0026gt; { { \u0026ldquo;Id\u0026rdquo;, CreateOrderingFunc\u0026lt;IDocument, Guid\u0026gt;(p =\u0026gt; p.Id) }, { \u0026ldquo;Inactive\u0026rdquo;, CreateOrderingFunc\u0026lt;IDocument, bool?\u0026gt;(p =\u0026gt; p.Inactive ) }, { \u0026ldquo;Timestamp\u0026rdquo;, CreateOrderingFunc\u0026lt;IDocument, DateTime?\u0026gt;(p =\u0026gt; p.Timestamp ) } };\nprivate static Func\u0026amp;lt;IQueryable\u0026amp;lt;T\u0026amp;gt;, bool, IOrderedQueryable\u0026amp;lt;T\u0026amp;gt;\u0026amp;gt; CreateOrderingFunc\u0026amp;lt;T, TKey\u0026amp;gt;(Expression\u0026amp;lt;Func\u0026amp;lt;T, TKey\u0026amp;gt;\u0026amp;gt; keySelector) { return (source, @ascending) =\u0026amp;gt; @ascending ? source.OrderBy(keySelector) : source.OrderByDescending(keySelector); } public IEnumerable\u0026amp;lt;IDocument\u0026amp;gt; GetDocuments(out int totalRecords, int pageSize, int pageIndex, string sort, SortDirection sortOrder) { using (var context = new EDM()) { IQueryable\u0026amp;lt;IDocument\u0026amp;gt; documents = context.Documents; totalRecords = documents.Count(); Func\u0026amp;lt;IQueryable\u0026amp;lt;IDocument\u0026amp;gt;, bool, IOrderedQueryable\u0026amp;lt;IDocument\u0026amp;gt;\u0026amp;gt; applyOrdering; _documentOrderings.TryGetValue(sort, out applyOrdering); documents = applyOrdering(documents, sortOrder == SortDirection.Ascending); if (pageSize \u0026amp;gt; 0 \u0026amp;amp;\u0026amp;amp; pageIndex \u0026amp;gt;= 0) { documents = documents.Skip(pageIndex * pageSize).Take(pageSize); } return documents.ToList(); } } }\nNow for the Controller to process the data:\nusing System; using System.Web.Mvc; using Domain; using Models; public class HomeController : Controller { private readonly IDocumentService _documentService; public HomeController() { _documentService = new EfDocumentService(); } public ActionResult index(int page = 1, string sort = \u0026quot;Id\u0026quot;, string sortDir = \u0026quot;Ascending\u0026quot;) { const int pageSize = 5; int totalRecords; var documents = _documentService.GetDocuments(out totalRecords, pageSize: pageSize, pageIndex: page - 1, sort: sort, sortOrder: GetSortDirection(sortDir)); var model = new PagedDocumentsModel { PageSize = pageSize, PageNumber = page, Documents = documents, TotalRows = totalRecords }; return View(model); } private SortDirection GetSortDirection(string sortDirection) { if (sortDirection != null) { if (sortDirection.Equals(\u0026quot;DESC\u0026quot;, StringComparison.OrdinalIgnoreCase) || sortDirection.Equals(\u0026quot;DESCENDING\u0026quot;, StringComparison.OrdinalIgnoreCase)) { return SortDirection.Ascending; } } return SortDirection.Descending; } }\u0026lt;/pre\u0026gt; The model to display all the information to the screen:\nusing System.Collections.Generic; using Domain; public class PagedDocumentsModel { public int PageSize { get; set; } public int PageNumber { get; set; } public IEnumerable\u0026lt;IDocument\u0026gt; Documents { get; set; } public int TotalRows { get; set; } }\nAnd finally the view to display the information:\n@model WebGridPaging.Models.PagedDocumentsModel @using WebGridPaging.Infrastructure @{ Layout = null; } \u0026lt;!DOCTYPE html\u0026gt; \u0026lt;html\u0026gt; \u0026lt;head\u0026gt; \u0026lt;meta name=\"viewport\" content=\"width=device-width\" /\u0026gt; \u0026lt;script src=\"../../Scripts/jquery-2.0.3.min.js\" type=\"text/javascript\"\u0026gt;\u0026lt;/script\u0026gt; \u0026lt;title\u0026gt;List\u0026lt;/title\u0026gt; \u0026lt;/head\u0026gt; \u0026lt;body\u0026gt; \u0026lt;div id=\"grid\"\u0026gt; @{ var grid = new WebGrid\u0026lt;WebGridPaging.Domain.IDocument\u0026gt;(null, rowsPerPage: Model.PageSize, defaultSort: \"Id\", ajaxUpdateContainerId:\"grid\"); grid.Bind(Model.Documents, rowCount: Model.TotalRows, autoSortAndPage: false); } @grid.GetHtml() \u0026lt;/div\u0026gt; \u0026lt;p\u0026gt; Model.Documents.Count() = @Model.Documents.Count() \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; Model.TotalRows = @Model.TotalRows \u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; Time = @System.DateTime.Now \u0026lt;/p\u0026gt; \u0026lt;/body\u0026gt; \u0026lt;/html\u0026gt; I’ve included a project with code samples, but please note this is talking to an external database with a table called Documents, so either generate a sample database with this table or point it to one you already have.\nWebGridPaging.zip (3.37 mb)\nReference links\nGet the Most out of WebGrid in ASP.NET MVC\n","date":"15 October 2013","externalUrl":null,"permalink":"/using-the-webgrid-in-mvc-correctly/","section":"Articles","summary":"I know the WebGrid is a basic Grid control, but sometimes you are constrained with what you can use with a customer and WebGrid is by default from Microsoft so it is safe to use and does not require any unknown third party tools to be installed.\n","title":"Using the WebGrid in MVC correctly","type":"articles"},{"content":"We all use the excellent ELMAH to deal with unhandled exceptions in an ASP.NET 3.5 web or MVC application. This works extremely well for all of the site, now what about WCF how can we get Elmah to work for us?\nYou can use the HttpHandler, and Decorate your Service(s) with an Error Handling attribute.\nThe ServiceErrorBehaviourAttribute:\nusing System; using System.Collections.ObjectModel; using System.Linq; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; /// \u0026lt;summary\u0026gt; /// So we can decorate Services with the [ServiceErrorBehaviour(typeof(HttpErrorHandler))] /// \u0026hellip;and errors reported to ELMAH /// \u0026lt;/summary\u0026gt; public class ServiceErrorBehaviourAttribute : Attribute, IServiceBehavior { readonly Type _errorHandlerType;\npublic ServiceErrorBehaviourAttribute(Type errorHandlerType) { this._errorHandlerType = errorHandlerType; } public void Validate(ServiceDescription description, ServiceHostBase serviceHostBase) { } public void AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHostBase, Collection\u0026amp;lt;ServiceEndpoint\u0026amp;gt; endpoints, BindingParameterCollection parameters) { } public void ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase) { var errorHandler = (IErrorHandler)Activator.CreateInstance(_errorHandlerType); foreach (var channelDispatcher in serviceHostBase.ChannelDispatchers.OfType\u0026amp;lt;ChannelDispatcher\u0026amp;gt;()) { channelDispatcher.ErrorHandlers.Add(errorHandler); } } }\nNow the HttpErrorHandler:\nusing Elmah; using System; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; /// \u0026lt;summary\u0026gt; /// Your handler to actually tell ELMAH about the problem. /// \u0026lt;/summary\u0026gt; public class HttpErrorHandler : IErrorHandler { public bool HandleError(Exception error) { return false; }\npublic void ProvideFault(Exception error, MessageVersion version, ref Message fault) { if (error == null) return; ErrorLog.GetDefault(null).Log(new Error(error)); } }\nNow it is just a simple case of adding an attribute to the WCF Service:\n[ServiceErrorBehaviour(typeof(HttpErrorHandler))] public class Game : IGame { Here is a small sample application showing it in action\nWcfService1.zip (8.26 kb)\n","date":"9 October 2013","externalUrl":null,"permalink":"/catching-exceptions-with-elmah-within-wcf/","section":"Articles","summary":"We all use the excellent ELMAH to deal with unhandled exceptions in an ASP.NET 3.5 web or MVC application. This works extremely well for all of the site, now what about WCF how can we get Elmah to work for us?\n","title":"Catching Exceptions with Elmah within WCF","type":"articles"},{"content":"There are many ways to search a system, what we have to be careful of is making sure that the search does not cause a DoS (Denial of Service) attack.\nSo following on from my article Denial Of Service (DoS) attacks via SQL Wildcards should be prevented here is a method to remove and clean up the search to prevent such an attack.\nusing System; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Collections.Specialized; public class Search { private readonly Regex RegexStripHtml = new Regex(\u0026quot;\u0026lt;[^\u0026gt;]*\u0026gt;\u0026quot;, RegexOptions.Compiled);\nprivate StringCollection StopWords { get { var stopWords = new StringCollection(); // Add your stopword here, or get them from a data source return stopWords; } }\npublic string CleanContent(string content, bool removeHtml) { if (removeHtml) { content = StripHtml(content); }\ncontent = content.Replace(\u0026quot;\\\\\u0026quot;, string.Empty).Replace(\u0026quot;|\u0026quot;, string.Empty).Replace(\u0026quot;(\u0026quot;, string.Empty).Replace( \u0026quot;)\u0026quot;, string.Empty).Replace(\u0026quot;[\u0026quot;, string.Empty).Replace(\u0026quot;]\u0026quot;, string.Empty).Replace(\u0026quot;*\u0026quot;, string.Empty). Replace(\u0026quot;?\u0026quot;, string.Empty).Replace(\u0026quot;}\u0026quot;, string.Empty).Replace(\u0026quot;{\u0026quot;, string.Empty).Replace( \u0026quot;^\u0026quot;, string.Empty).Replace(\u0026quot;+\u0026quot;, string.Empty).Replace(\u0026quot;%\u0026quot;, string.Empty).Replace(\u0026quot;_\u0026quot;, string.Empty); var words = content.Split(new[] { ' ', '\\n', '\\r' }, StringSplitOptions.RemoveEmptyEntries); var sb = new StringBuilder(); foreach (var word in words.Select(t =\u0026amp;gt; t.ToLowerInvariant().Trim()).Where(word =\u0026amp;gt; word.Length \u0026amp;gt; 1 \u0026amp;amp;\u0026amp;amp; !StopWords.Contains(word))) { sb.AppendFormat(\u0026quot;{0} \u0026quot;, word); } return sb.ToString().Trim(); }\nprivate string StripHtml(string html) { return StringIsNullOrWhitespace(html) ? string.Empty : RegexStripHtml.Replace(html, string.Empty).Trim(); }\nprivate bool StringIsNullOrWhitespace(string value) { return ((value == null) || (value.Trim().Length == 0)); }\nSome of this code was cribbed from the BlogEngine\nHere are some Unit Tests to test the CleanCode method, yes Unit Tests, this is the perfect method to perform and under how the methodworks.\nusing Microsoft.VisualStudio.TestTools.UnitTesting; using Capita.Dolphin.Web.Helpers; /// \u0026lt;summary\u0026gt; /// Summary description for HelperSearchTests /// \u0026lt;/summary\u0026gt; [TestClass] public class HelperSearchTests { [TestMethod] public void CleanContentValidCharacters() { // Assign var search = new Search(); const string expected = \u0026ldquo;hello moon\u0026rdquo;;\n// Act var actual = search.CleanContent(\u0026quot;Hello moon\u0026quot;, false); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void CleanContentInValidCharacters() { // Assign var search = new Search(); const string expected = \u0026quot;hello moon\u0026quot;; // Act var actual = search.CleanContent(\u0026quot;Hello moo%*([|+^}{)n\u0026quot;, false); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void CleanContentRemoveHTMLCharacters() { // Assign var search = new Search(); const string expected = \u0026quot;hello moon\u0026quot;; // Act var actual = search.CleanContent(\u0026quot;\u0026amp;lt;p\u0026amp;gt;Hello moon\u0026amp;lt;/p\u0026amp;gt;\u0026quot;, true); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void CleanContentRemoveExtraWildCardsCharacters() { // Assign var search = new Search(); const string expected = \u0026quot;hello moon\u0026quot;; // Act var actual = search.CleanContent(\u0026quot;[][^]_%Hello moon\u0026amp;lt;/p\u0026amp;gt;\u0026quot;, true); // Assert Assert.AreEqual(expected, actual); } }\n","date":"8 October 2013","externalUrl":null,"permalink":"/removing-and-cleaning-search-content-to-prevent-dos-attacks/","section":"Articles","summary":"There are many ways to search a system, what we have to be careful of is making sure that the search does not cause a DoS (Denial of Service) attack.\nSo following on from my article Denial Of Service (DoS) attacks via SQL Wildcards should be prevented here is a method to remove and clean up the search to prevent such an attack.\n","title":"Removing and Cleaning search content to prevent DoS attacks","type":"articles"},{"content":"Following on from my article about checking for the file signature to ensure that the file is who it says it is\nI decide to take it further and produce a Data Validation attribute, I found that the Microsoft.Web.Mvc.dll library already has one ,but it only checks for the file names, which is generally okay.\nSo I thought I’d enhance the Microsoft FileExtension attribute, but it was sealed……! Grrrrrrrr But Microsoft now have most of its code as open source, yaaaaa 🙂\nSo I downloaded the source and created my own variation of the FileExtensionsAttribute\nFirst we need to generate DataTypeAttribute, and IClientValidatable to inherit.\nIClientValidatable using System.Collections.Generic; using System.Web.Mvc; public interface IClientValidatable { IEnumerable\u0026lt;ModelClientValidationRule\u0026gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context); }\nModelClientValidationRule using System; using System.Collections.Generic; using System.Runtime.CompilerServices; [TypeForwardedFrom(\u0026ldquo;System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\u0026rdquo;)] public class ModelClientValidationRule { private readonly Dictionary\u0026lt;string, object\u0026gt; _validationParameters = new Dictionary\u0026lt;string, object\u0026gt;(); private string _validationType;\npublic string ErrorMessage { get; set; } public IDictionary\u0026amp;lt;string, object\u0026amp;gt; ValidationParameters { get { return _validationParameters; } } public string ValidationType { get { return _validationType jQuery15201478678032162548_1380881227039 String.Empty; } set { _validationType = value; } } }\nNow the actual code for FileExtensionsAttribute\nFileExtensionsAttribute using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using DataValidation.Properties; /// \u0026lt;summary\u0026gt; /// The file extensions, default is png,jpg,jpeg,gif. /// \u0026lt;/summary\u0026gt; [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class FileExtensionsAttribute : DataTypeAttribute, IClientValidatable { private string _extensions; private string _extensionsSignatures;\npublic FileExtensionsAttribute() : base(\u0026quot;upload\u0026quot;) { ErrorMessage = DataValidationResource.FileExtensionsAttribute_Invalid; } /// \u0026amp;lt;summary\u0026amp;gt; /// The file extensions, default is png,jpg,jpeg,gif. /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;value\u0026amp;gt; /// The extensions. /// \u0026amp;lt;/value\u0026amp;gt; public string Extensions { get { return String.IsNullOrWhiteSpace(_extensions) ? \u0026quot;png,jpg,jpeg,gif\u0026quot; : _extensions; } set { _extensions = value; } } /// \u0026amp;lt;summary\u0026amp;gt; /// The extensions signatures, this is the fileclass signature within the actual file. /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;value\u0026amp;gt; /// The extensions signatures. /// \u0026amp;lt;/value\u0026amp;gt; public string ExtensionsSignatures { get { return String.IsNullOrWhiteSpace(_extensionsSignatures) ? \u0026quot;\u0026quot; : _extensionsSignatures; } set { _extensionsSignatures = value; } } private string ExtensionsFormatted { get { return ExtensionsParsed.Aggregate((left, right) =\u0026amp;gt; left + \u0026quot;, \u0026quot; + right); } } [SuppressMessage(\u0026quot;Microsoft.Globalization\u0026quot;, \u0026quot;CA1308:NormalizeStringsToUppercase\u0026quot;, Justification = \u0026quot;These strings are normalized to lowercase because they are presented to the user in lowercase format\u0026quot;)] private string ExtensionsNormalized { get { return Extensions.Replace(\u0026quot; \u0026quot;, String.Empty).Replace(\u0026quot;.\u0026quot;, String.Empty).ToLowerInvariant(); } } [SuppressMessage(\u0026quot;Microsoft.Globalization\u0026quot;, \u0026quot;CA1308:NormalizeStringsToUppercase\u0026quot;, Justification = \u0026quot;These strings are normalized to lowercase because they are presented to the user in lowercase format\u0026quot;)] private string ExtensionsSignaturesNormalized { get { return ExtensionsSignatures.Replace(\u0026quot; \u0026quot;, String.Empty).Replace(\u0026quot;.\u0026quot;, String.Empty).ToLowerInvariant(); } } private IEnumerable\u0026amp;lt;string\u0026amp;gt; ExtensionsParsed { get { return ExtensionsNormalized.Split(',').Select(e =\u0026amp;gt; \u0026quot;.\u0026quot; + e); } } private IEnumerable\u0026amp;lt;string\u0026amp;gt; ExtensionsSignaturesParsed { get { return ExtensionsSignaturesNormalized.Split(','); } } public override string FormatErrorMessage(string name) { return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, ExtensionsFormatted); } public IEnumerable\u0026amp;lt;ModelClientValidationRule\u0026amp;gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ValidationType = \u0026quot;extension\u0026quot;, ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()) }; rule.ValidationParameters[\u0026quot;extension\u0026quot;] = ExtensionsNormalized; yield return rule; } public override bool IsValid(object value) { if (value == null) { return true; } var valueAsFileBase = value as HttpPostedFileBase; if (valueAsFileBase != null) { return ValidateExtension(valueAsFileBase.FileName) \u0026amp;amp;\u0026amp;amp; ValidateFileContent(valueAsFileBase); } var valueAsString = value as string; return valueAsString != null \u0026amp;amp;\u0026amp;amp; ValidateExtension(valueAsString); } [SuppressMessage(\u0026quot;Microsoft.Globalization\u0026quot;, \u0026quot;CA1308:NormalizeStringsToUppercase\u0026quot;, Justification = \u0026quot;These strings are normalized to lowercase because they are presented to the user in lowercase format\u0026quot;)] private bool ValidateExtension(string fileName) { try { return ExtensionsParsed.Contains(Path.GetExtension(fileName).ToLowerInvariant()); } catch (ArgumentException) { return false; } } private bool ValidateFileContent(HttpPostedFileBase file) { var validExtensions = GetValidExtenstions(); var br = new BinaryReader(file.InputStream); string fileclass; byte buffer; try { buffer = br.ReadByte(); fileclass = buffer.ToString(); buffer = br.ReadByte(); fileclass += buffer.ToString(); } catch { return false; } return string.IsNullOrWhiteSpace(ExtensionsSignatures) ? ExtensionsParsed.Where(validExtensions.ContainsKey).Any(extension =\u0026amp;gt; validExtensions[extension].ToString() == fileclass) : ExtensionsSignaturesParsed.Any(extensionsSignatures =\u0026amp;gt; extensionsSignatures == fileclass); } private Dictionary\u0026amp;lt;string, int\u0026amp;gt; GetValidExtenstions() { var validExtenstions = new Dictionary\u0026amp;lt;string, int\u0026amp;gt; { {\u0026quot;.gif\u0026quot;, 7173}, {\u0026quot;.jpg\u0026quot;, 255216}, {\u0026quot;.png\u0026quot;, 13780}, {\u0026quot;.bmp\u0026quot;, 6677}, {\u0026quot;.txt\u0026quot;, 239187}, {\u0026quot;/\u0026quot;, 239187}, {\u0026quot;.asp\u0026quot;, 239187}, {\u0026quot;.sql\u0026quot;, 239187}, {\u0026quot;.xls\u0026quot;, 208207}, {\u0026quot;.doc\u0026quot;, 208207}, {\u0026quot;.docx\u0026quot;, 208207}, {\u0026quot;.dot\u0026quot;, 208207}, {\u0026quot;.dotx\u0026quot;, 208207}, {\u0026quot;.ppt\u0026quot;, 208207}, {\u0026quot;.xml\u0026quot;, 6063}, {\u0026quot;.html\u0026quot;, 6033}, {\u0026quot;.js\u0026quot;, 4742}, {\u0026quot;.xlsx\u0026quot;, 8075}, {\u0026quot;.zip\u0026quot;, 8075}, {\u0026quot;.ptx\u0026quot;, 8075}, {\u0026quot;.mmap\u0026quot;, 8075}, {\u0026quot;.rar\u0026quot;, 8297}, {\u0026quot;.accdb\u0026quot;, 01}, {\u0026quot;.mdb\u0026quot;, 01}, {\u0026quot;.exe\u0026quot;, 7790}, {\u0026quot;.dll\u0026quot;, 7790}, {\u0026quot;.bat\u0026quot;, 64101}, {\u0026quot;.tiff\u0026quot;, 7373}, {\u0026quot;.tif\u0026quot;, 7373} }; return validExtenstions; } }\nYou’ll notice the ValidateFileContent method which is the additional feature I’ve added to check for the file signature.\nThat’s it job done\nA sample project can be found here\nFileUploader.zip (9.24 mb)\n","date":"4 October 2013","externalUrl":null,"permalink":"/mvc-way-to-check-the-file-extension/","section":"Articles","summary":"Following on from my article about checking for the file signature to ensure that the file is who it says it is\nI decide to take it further and produce a Data Validation attribute, I found that the Microsoft.Web.Mvc.dll library already has one ,but it only checks for the file names, which is generally okay.\n","title":"MVC way to check the File Extension","type":"articles"},{"content":"Is it possible to upload files of any type to the server through web application’s functionality?\nOnly file extension restrictions were could be enforced and the server may not perform any content checking (apart from possible anti-virus checks).\nAt the very least, a rudimentary check of the file content/headers must be made to ensure that the file extension does relate to the file content and that both are acceptable for uploading into the system.\nIdeally the file content must be checked to ensure no malicious scripts or macros in word documents are present. Recommendation: All uploaded files should be thoroughly scanned and validated before being made available to other users.\nIf in doubt, the file should be discarded. Ideally, only files of certain types should be allowed and checking for file types should be done by the server for their content and file extensions, Content-Encoding or Content-Type headers should not be relied upon.\nI’ve produced a simple application that checks for file signature when upload that can be used\nhttps://bryanavery.co.uk/post/2013/06/25/Determine-which-file-type-has-been-uploaded/\nAnothe rsource of reference can he found here:\nhttp://stackoverflow.com/questions/58510/using-net-how-can-you-find-the-mime-type-of-a-file-based-on-the-file-signature\n","date":"3 October 2013","externalUrl":null,"permalink":"/file-upload-does-not-check-content/","section":"Articles","summary":"Is it possible to upload files of any type to the server through web application’s functionality?\nOnly file extension restrictions were could be enforced and the server may not perform any content checking (apart from possible anti-virus checks).\n","title":"File Upload does not check content","type":"articles"},{"content":"A vulnerability exists in SSL 3.0 and TLS 1.0 that could allow information disclosure if an attacker intercepts encrypted traffic served from an affected system. The weakness is down to insufficiently randomised data being used for the Initialisation Vectors (IV) within the CBC-mode encryption algorithms. The exploit can be performed through multiple injection points, both native to the browser’s functionality.\nThis issue is reduced in risk by the fact that the attacker is required to have a Man-in-the-Middle position for this exploit whereby traffic interception can be performed, and with this position obtained it is generally easier to attack the victim through other methods (SSL-stripping, mixed-scripting [requesting HTTP resources from an HTTPS connection], etc…) which do not require complex cryptanalysis such as BEAST to execute.\nTestSSLServer.exe (43.00 kb)\nhttp://www.bolet.org/TestSSLServer/\nSupported versions: SSLv2 SSLv3 TLSv1.0 Deflate compression: no Supported cipher suites (ORDER IS NOT SIGNIFICANT): SSLv2 RC4_128_WITH_MD5 DES_192_EDE3_CBC_WITH_MD5 SSLv3 RSA_WITH_RC4_128_MD5 RSA_WITH_RC4_128_SHA RSA_WITH_3DES_EDE_CBC_SHA TLSv1.0 RSA_WITH_RC4_128_MD5 RSA_WITH_RC4_128_SHA RSA_WITH_3DES_EDE_CBC_SHA RSA_WITH_AES_128_CBC_SHA RSA_WITH_AES_256_CBC_SHA TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA ---------------------- Server certificate(s): 0edc8b5e2d1e4c803319c3e4e80dd9945d953db2: CN=application.local.someone.zone ---------------------- Minimal encryption strength: strong encryption (96-bit or more) Achievable encryption strength: strong encryption (96-bit or more) BEAST status: vulnerable CRIME status: protected Recommendation: Client-side: Various browsers are introducing or have introduced mitigations for the issue which make exploitation less likely. There are also steps which can be taken on the server side to make exploitation impossible. Server-side: Enabling and prioritising TLS 1.1/1.2 would be advised where possible although removing support for TLS1.0 is impractical at this time.\nIn the short-term due to the lack of wide-scale support by browsers and servers alike, prioritising the use of a stream cipher (such as RC4-SHA) instead of a CBC-mode cipher is recommended in order to maintain compatibility with browsers (see note).\nMigration away from TLS 1.0 and below to TLS 1.1/1.2 should considered as a medium-term option for secure applications.\nSSL Best Practice Guide: https://www.ssllabs.com/projects/best-practices/index.html BEAST attack On September 23, 2011 researchers Thai Duong and Juliano Rizzo demonstrated a “proof of concept” called BEAST (“Browser Exploit Against SSL/TLS”) using a Java applet to violate same origin policy constraints, for a long-known Cipher block chaining (CBC) vulnerability in TLS 1.0.[44][45] Practical exploits had not been previously demonstrated for this vulnerability, which was originally discovered by Phillip Rogaway[46] in 2002. The vulnerability of the attack had been fixed with TLS 1.1 in 2006, but TLS 1.1 had not seen wide adoption prior to this attack demonstration.\nMozilla updated the development versions of their NSS libraries to mitigate BEAST-like attacks. NSS is used by Mozilla Firefox and Google Chrome to implement SSL. Some web servers that have a broken implementation of the SSL specification may stop working as a result.\nMicrosoft released Security Bulletin MS12-006 on January 10, 2012, which fixed the BEAST vulnerability by changing the way that the Windows Secure Channel (SChannel) component transmits encrypted network packets.\nUsers of Windows 7 and Windows Server 2008 R2 can enable use of TLS 1.1 and 1.2, but this work-around will fail if it is not supported by the other end of the connection and will result in a fall-back to TLS 1.0.\n","date":"3 October 2013","externalUrl":null,"permalink":"/ssl-vulnerable-to-beast-attack/","section":"Articles","summary":"A vulnerability exists in SSL 3.0 and TLS 1.0 that could allow information disclosure if an attacker intercepts encrypted traffic served from an affected system. The weakness is down to insufficiently randomised data being used for the Initialisation Vectors (IV) within the CBC-mode encryption algorithms. The exploit can be performed through multiple injection points, both native to the browser’s functionality.\n","title":"SSL Vulnerable to BEAST attack","type":"articles"},{"content":"The software generates an error message that includes sensitive information about its environment, users, or associated data. Extended Description The sensitive information may be valuable information on its own (such as a password), or it may be useful for launching other, more deadly attacks. If an attack fails, an attacker may use error information provided by the server to launch another more focused attack. For example, an attempt to exploit a path traversal weakness might yield the full pathname of the installed application. In turn, this could be used to select the proper number of “..” sequences to navigate to the targeted file. An attack using SQL injection might not initially succeed, but an error message could reveal the malformed query, which would expose query logic and possibly even passwords or other sensitive information used within the query. Recommendation Suppress these error messages by ensuring that a customised error handler is called in the event of an error. This can produce a generic message which does not hint at the underlying cause of the exception. References OWASP – Error Handling\nhttp://www.owasp.org/index.php/Improper_Error_Handling How to: Display Safe Error Messages When your application displays error messages, it should not give away information that a malicious user might find helpful in attacking your system. For example, if your application unsuccessfully tries to log in to a database, it should not display an error message that includes the user name it is using.\nThere are a number of ways to control error messages, including the following:\nConfigure the application not to show verbose error messages to remote users. (Remote users are those who request pages while not working on the Web server computer.) You can optionally redirect errors to an application page.\nInclude error handling whenever practical and construct your own error messages. In your error handler, you can test to see whether the user is local and react accordingly.\nCreate a global error handler at the page or application level that catches all unhandled exceptions and routes them to a generic error page. That way, even if you did not anticipate a problem, at least users will not see an exception page.\nTo configure the application to turn off errors for remote users\nIn the Web.config file for your application, make the following changes to the customErrors element:\nSet the mode attribute to RemoteOnly (case-sensitive). This configures the application to show detailed errors only to local users (that is, to you, the developer). Optionally include a defaultRedirect attribute that points to an application error page. Optionally include \u0026lt;error\u0026gt; elements that redirect specific errors to specific pages. For example, you can redirect standard 404 errors (page not found) to your own application page. The following code example shows a typical customErrors block in the Web.config file. \u0026lt;customErrors mode=\"RemoteOnly\" defaultRedirect=\"AppErrors/\"\u0026gt; \u0026lt;error statusCode=\"404\" redirect=\"NoSuchPage/\"/\u0026gt; \u0026lt;error statusCode=\"403\" redirect=\"NoAccessAllowed/\"/\u0026gt; \u0026lt;/customErrors\u0026gt; ","date":"3 October 2013","externalUrl":null,"permalink":"/verbose-error-messages/","section":"Articles","summary":"The software generates an error message that includes sensitive information about its environment, users, or associated data. Extended Description The sensitive information may be valuable information on its own (such as a password), or it may be useful for launching other, more deadly attacks. If an attack fails, an attacker may use error information provided by the server to launch another more focused attack. For example, an attempt to exploit a path traversal weakness might yield the full pathname of the installed application. In turn, this could be used to select the proper number of “..” sequences to navigate to the targeted file. An attack using SQL injection might not initially succeed, but an error message could reveal the malformed query, which would expose query logic and possibly even passwords or other sensitive information used within the query. ","title":"Verbose Error Messages","type":"articles"},{"content":"Certificate is singed by an unrecognised certificate authority. If a browser receives a self-signed certificate, it pops up a warning, and the burden falls to the user to confirm the identity. Pushing this decision to the user is ultimately what opens up the possibility of a man-in-the-middle (MITM) attack. The security issue is not with self-signed certificates, but with the way users interact with them in the browser.\nRecommendation: Purchase or generate a proper certificate for this service.\nCheck out, for Mand in the middle\nhttp://www.schneier.com/blog/archives/2010/04/man-in-the-midd_2.html\nYou can purchase SSL certificates from Symantec\nhttps://www.symantec.com/en/uk/verisign/ssl-certificates/secure-site\n","date":"3 October 2013","externalUrl":null,"permalink":"/environment-issue-untrusted-certificate/","section":"Articles","summary":"Certificate is singed by an unrecognised certificate authority. If a browser receives a self-signed certificate, it pops up a warning, and the burden falls to the user to confirm the identity. Pushing this decision to the user is ultimately what opens up the possibility of a man-in-the-middle (MITM) attack. The security issue is not with self-signed certificates, but with the way users interact with them in the browser.\n","title":"Environment issue – Untrusted Certificate","type":"articles"},{"content":"SQL Wildcard attacks force the underlying database to carry out CPU-intensive queries by using several wildcards. This vulnerability generally exists in search functionalities of web applications. Successful exploitation of this attack will cause Denial of Service (DoS).\nDepending on the connection pooling settings of the application and the time taken for attack query to execute, an attacker might be able to consume all connections in the connection pool, which will cause database queries to fail for legitimate users.\nBy default in ASP.NET, the maximum allowed connections in the pool is 100 and timeout is 30 seconds. Thus if an attacker can run 100 multiple queries with 30+ seconds execution time within 30 seconds no one else would be able to use the database related parts of the application.\nRecommendation If the application does not require this sort of advanced search, all wildcards should be escaped or filtered.\nReferences:\nOWASP Testing for SQL Wildcard Attacks\nhttps://www.owasp.org/index.php/Testing_for_SQL_Wildcard_Attacks_(OWASP-DS-001)\nDoS Attacks using SQL Wildcards\nhttp://www.zdnet.com/blog/security/dos-attacks-using-sql-wildcards-revealed/1134\nBrief Summary SQL Wildcard Attacks are about forcing the underlying database to carry out CPU-intensive queries by using several wildcards. This vulnerability generally exists in search functionalities of web applications. Successful exploitation of this attack will cause Denial of Service.\nDescription of the Issue SQL Wildcard attacks might affect all database back-ends but mainly affect SQL Server because the MS SQL Server LIKE operator supports extra wildcards such as “[]”,”[^]”,”_” and “%”.\nIn a typical web application, if you were to enter “foo” into the search box, the resulting SQL query might be:\nSELECT * FROM Article WHERE Content LIKE ‘%foo%’\nIn a decent database with 1-100000 records the query above will take less than a second. The following query, in the very same database, will take about 6 seconds with only 2600 records.\nSELECT TOP 10 * FROM Article WHERE Content LIKE ‘%_[^!_%/%a?F%_D)_(F%)_%([)({}%){()}£$\u0026amp;N%_)$*£()$*R”_)][%](%[x])%a][$*”£$-9]_%’\nSo, if the tester wanted to tie up the CPU for 6 seconds they would enter the following to the search box:\n_[^!_%/%a?F%_D)_(F%)_%([)({}%){()}£$\u0026amp;N%_)$*£()$*R”_)][%](%[x])%a][$*”£$-9]_\nBlack Box testing and example Testing for SQL Wildcard Attacks: Craft a query which will not return a result and includes several wildcards. You can use one of the example inputs below.\nSend this data through the search feature of the application. If the application takes more time generating the result set than a usual search would take, it is vulnerable.\nExample Attack Inputs to send\n‘%_[^!_%/%a?F%_D)_(F%)_%([)({}%){()}£$\u0026amp;N%_)$*£()$*R”_)][%](%[x])%a][$*”£$-9]_%’\n‘%64_[^!_%65/%aa?F%64_D)_(F%64)_%36([)({}%33){()}£$\u0026amp;N%55_)$*£()$*R”_)][%55](%66[x])%ba][$*”£$-9]_%54’ bypasses modsecurity\n_[r/a)_ _(r/b)_ _(r-d)_\n%n[^n]y[^j]l[^k]d[^l]h[^z]t[^k]b[^q]t[^q][^n]!%\n%_[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[! -z]@$!_%\n…\nResult Expected If the application is vulnerable, the response time should be longer than usual.\nSQL Wildcard attacks force the underlying database to carry out CPU-intensive queries by using several wildcards. This vulnerability generally exists in search functionalities of web applications. Successful exploitation of this attack will cause Denial of Service. Here, it was possible to search by keying in a value for the forename/firstname field as M__E (i.e. M underscore underscore E) and the search returned results treating the two underscores as wildcards for any two characters.\nThis may still exist on the current code base so it’s a case of going through the forms and ensuring that it doesn’t occur / fix it if the vulnerability exists.\nDoS Attacks Using SQL Wiltcards.pdf (567.23 kb)\nCheck the solution I have produced to prevent this Removing and Cleaning search content to prevent DoS attacks\n","date":"1 October 2013","externalUrl":null,"permalink":"/denial-of-service-dos-attacks-via-sql-wildcards-should-be-prevented/","section":"Articles","summary":"SQL Wildcard attacks force the underlying database to carry out CPU-intensive queries by using several wildcards. This vulnerability generally exists in search functionalities of web applications. Successful exploitation of this attack will cause Denial of Service (DoS).\n","title":"Denial Of Service (DoS) attacks via SQL Wildcards should be prevented","type":"articles"},{"content":"Vulnerability overview/description Due to unsanitized user input it is possible to inject arbitrary HTTP header values in certain HTTP responses of the Satellite Server. This can be exploited, for example, to perform session fixation and malicious redirection attacks via the Set-Cookie and the Refresh headers. Moreover, the Satellite Server caches these HTTP responses with the injected HTTP header resulting in all further requests to the same resource being served with the poisoned HTTP response, while these objects remain in cache. Information Disclosure Information disclosure enables an attacker to gain valuable information about a system. Therefore, always consider what information you are revealing and whether it can be used by a malicious user. The following lists possible information disclosure attacks and provides mitigations for each. Message Security and HTTP If you are using message-level security over an HTTP transport layer, be aware that message-level security does not protect HTTP headers. The only way to protect HTTP headers is to use HTTPS transport instead of HTTP. HTTPS transport causes the entire message, including the HTTP headers, to be encrypted using the Secure Sockets Layer (SSL) protocol.\nhttp://msdn.microsoft.com/en-us/library/aa738441/ Environment change The web application returned information about itself in the HTTP header that could aid an attacker. Default web server installations often include the vendor and version details of the web application, and possibly further information about scripting services also installed\n","date":"1 October 2013","externalUrl":null,"permalink":"/http-header-disclosure/","section":"Articles","summary":"Vulnerability overview/description Due to unsanitized user input it is possible to inject arbitrary HTTP header values in certain HTTP responses of the Satellite Server. This can be exploited, for example, to perform session fixation and malicious redirection attacks via the Set-Cookie and the Refresh headers. Moreover, the Satellite Server caches these HTTP responses with the injected HTTP header resulting in all further requests to the same resource being served with the poisoned HTTP response, while these objects remain in cache. ","title":"HTTP Header Disclosure","type":"articles"},{"content":"Is it possible to enumerate user account details within the Web application via the logon page?\nWhere an application requires account details to retrieve other information, it may be possible to enumerate the details based on the error message returned by the application.\nIn this case it was also possible to determine the state of the user account\nRecommendation: Messages which allow an attacker to enumerate account details should be removed. A generic error message which does not disclose information about account information should be used.\nReferences: OWASP Testing for user enumeration\nhttps://www.owasp.org/index.php/Testing_for_user_enumeration_(OWASP-AT-002)\nEnumeration\nEnumeration is the first attack on target network, enumeration is the process to gather the information about a target machine by actively connecting to it. Enumeration means to identify the user account, system account and admin account. Enumerating windows active directory to find out these stuffs. Discovering NetBIOS name enumeration with NBTscan. Establishing null sessions and connections. Null sessions tools like Dumpsec, Winfo and Sid2User or more, may used to perform this attack. The login failure messages can give away too much information and it would be possible to enumerate user details via the log-on page. It reports on whether an account exists/not and if an account is locked out or not etc.\nThere should ideally be just one generic message that’s of no use to a potential hacker.\n– See more at: http://www.ehacking.net/2011/04/scanning-and-enumeration-second-step-of.html#sthash.B3KW4Kcs.dpuf\nOther Considerations You’ll need to log somewhere in your application the actual reasons why the user could not login, this could be that the account is locked, suspened, deleted etc. By logging this information a system adminstrator or the like can see why a user could not get access to the application through the login page.\n","date":"1 October 2013","externalUrl":null,"permalink":"/user-enumeration-login-failure-messages-shouldnt-give-out-any-information-that-results-in-vulnerabilities/","section":"Articles","summary":"Is it possible to enumerate user account details within the Web application via the logon page?\nWhere an application requires account details to retrieve other information, it may be possible to enumerate the details based on the error message returned by the application.\n","title":"User Enumeration – Login failure messages shouldn’t give out any information that results in vulnerabilities.","type":"articles"},{"content":"I would like to secure up an MVC application, and one way of insuring a secure application is to run through pentesting, Penetration Testing, but what is pentesting?\nWikipedia\nA penetration test, occasionally pentest, is a method of evaluating computer and network security by simulating an attack on a computer system or network from external and internal threats. The process involves an active analysis of the system for any potential vulnerabilities that could result from poor or improper system configuration, both known and unknown hardware or software flaws, or operational weaknesses in process or technical countermeasures. This analysis is carried out from the position of a potential attacker and can involve active exploitation of security vulnerabilities.\nPentests should performed be by someone who has no involvement in the application lifecycle process, someone or some group of people who are independent and will try and penetrate the application. They will uncover security issues through penetration tests which are presented to the system’s owner. Effective penetration tests will couple this information with an accurate assessment of the potential impacts to the application and outline a range of technical and procedural countermeasures to reduce risks.\nPenetration tests are valuable for several reasons:\nDetermining the feasibility of a particular set of attack vectors Identifying higher-risk vulnerabilities that result from a combination of lower-risk vulnerabilities exploited in a particular sequence Identifying vulnerabilities that may be difficult or impossible to detect with automated network or application vulnerability scanning software Assessing the magnitude of potential business and operational impacts of successful attacks Testing the ability of network defenders to successfully detect and respond to the attacks Providing evidence to support increased investments in security personnel and technology In a series of blogs I will be going over everything that I find and document down how to overcome such vulnerabilities.\n","date":"1 October 2013","externalUrl":null,"permalink":"/pentest-where-to-start/","section":"Articles","summary":"I would like to secure up an MVC application, and one way of insuring a secure application is to run through pentesting, Penetration Testing, but what is pentesting?\nWikipedia\nA penetration test, occasionally pentest, is a method of evaluating computer and network security by simulating an attack on a computer system or network from external and internal threats. The process involves an active analysis of the system for any potential vulnerabilities that could result from poor or improper system configuration, both known and unknown hardware or software flaws, or operational weaknesses in process or technical countermeasures. This analysis is carried out from the position of a potential attacker and can involve active exploitation of security vulnerabilities.\n","title":"PenTest where to start","type":"articles"},{"content":" Enterprise Library Logging Application Block\nThe Enterprise Library Logging Application Block simplifies the implementation of common logging functions. You can use the Logging Application Block to write information to a variety of locations:\n· The event log\n· An e-mail message\n· A database\n· A message queue\n· A text file\n· A Windows® Management Instrumentation (WMI) event\n· Custom locations using application block extension points\nFeatures\n· Multiple targets can be configured\n· Enterprise Library Configuration Console available for easy configuration\n· Large number of options to be configured may make it a bit daunting to start with\n· Invasive – requires code change to implement logging\n· Logs all kinds of events/information, not just for error logging\n· Formatters available for formatting the event message\n· Log filters allow filtering of log messages\n· Facilities for WCF integration\n· It will take you a bit to get up to speed with Enterprise Library – it’s not a 5 second install.\n· There’s a lot of configuration to do in the app.config/web.config file just to make it work. That said, once you understand it, it easier on other projects.\n· You must implement the Logging Block, not just the Exception Handling Block to log the information somewhere (event log, flat file, database, etc.)\n· It’s not just for logging exceptions. For example, you may want to get log events for when a user logs in or logs out of an application.\n· You can use the configuration file to change how logging works depending on the environment (i.e. Log exceptions for Production, log everything for Dev, etc.).\n· It’s not just for web, but for all kinds of applications.\nELMAH\nELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.\nOnce ELMAH has been dropped into a running web application and configured appropriately, you get the following facilities without changing a single line of your code:\nLogging of nearly all unhandled exceptions.\nA web page to remotely view the entire log of recoded exceptions.\nA web page to remotely view the full details of any one logged exception, including coloured stack traces.\nIn many cases, you can review the original yellow screen of death that ASP.NET generated for a given exception, even with customErrors mode turned off.\nAn e-mail notification of each error at the time it occurs.\nAn RSS feed of the last 15 errors from the log.\nRuns using the Apache License (open source)\nComparison with ELMAH\nFeature/s\nLogging Application Block\nELMAH\nScope\nTrue enterprise level exception handling framework, across layers, tiers, processes and services (in tandem with Exception Handling Application Block) Logs all kinds of events, not just exceptions Lightweight logging framework with extension points for ASP.NET web applications By default logs unhandled exceptions Error signaling allows handled exceptions to be logged No support for non-error messages Targets supported\nThe event log An e-mail message A database (supports multiple) A message queue A text file A Windows® Management Instrumentation (WMI) event Custom locations using application block extension points Microsoft SQL Server Oracle (OracleErrorLog) SQLite (version 3) database file Microsoft Access (AccessErrorLog) Loose XML files RAM (in-memory) SQL Server Compact Edition MySQL PostgreSQL Pluggable?\nNo. Requires careful configuration and implementation in code\nFully pluggable out of the box, requires only configuration for basic features\nConfiguration\nXML configuration in the app.config/web.config as applicable Enterprise Library Configuration Console tool available for ease in configuration XML configuration in the web.config\nIntrusiveness\nRequires code change for implementation\nNo code change required for basic features\nExtensibility\nEasily extensible with multiple points for extensibility Easy to extend for log message formatting and contextual information No source code change required Requires change to source code for any kind of extensibility Error message formatting and contextual information addition requires source code changes Scalability\nEasily scales for small to medium sized applications Not enough data available for large sized applications Requires more research\nSummary\nThe Logging Application block beats ELMAH hands down in comprehensiveness. It can be used for logging all kinds of messages from all layers of various kinds of applications including ASP.NET, windows forms, WCF services etc. It can also be used for tracing for performance and debugging purposes.\nOn the other hand ELMAH is a light-weight framework for logging exceptions in ASP.NET applications.\nELMAH is very easy to configure and use. It is fully pluggable. Whereas implementation of the Logging Application block requires careful planning, configuration and is intrusive as it requires changes to code wherever logging is required.\nOne of the biggest benefits of the Enterprise Library is that it works in tandem with the Exception Handling block to implement a consistent strategy for processing exceptions in all the architectural tiers of an enterprise application including WCF Services.\nWhile ELMAH is perfect for ASP.NET applications, for enterprise applications the Enterprise Library fulfils the comprehensiveness required.\n","date":"29 August 2013","externalUrl":null,"permalink":"/elmah-or-microsoft-enterprise-library-for-exception-logging/","section":"Articles","summary":" Enterprise Library Logging Application Block\nThe Enterprise Library Logging Application Block simplifies the implementation of common logging functions. You can use the Logging Application Block to write information to a variety of locations:\n","title":"Elmah or Microsoft Enterprise Library for Exception logging","type":"articles"},{"content":"I need to stop caching across all browsers of my website for security reasons. This has been driving me nuts over the past two weeks, as every method I try just keep allow some caching to be stored. Easiest way to check is by pressing the back key on the browsers window as the results should update.\nI finally found a solution\nusing HTML:\n\u0026lt;meta http-equiv=\"Cache-Control\" content=\"no-cache, no-store, must-revalidate\" /\u0026gt; \u0026lt;meta http-equiv=\"Pragma\" content=\"no-cache\" /\u0026gt; \u0026lt;meta http-equiv=\"Expires\" content=\"0\" /\u0026gt; In ASP.NET\nResponse.AppendHeader(\"Cache-Control\", \"no-cache, no-store, must-revalidate\"); // HTTP 1.1. Response.AppendHeader(\"Pragma\", \"no-cache\"); Response.AppendHeader(\"Expires\", \"0\"); The Cache-Control is per the HTTP 1.1 spec for clients (and implicitly required by some browsers next to Expires), the Pragma is per the HTTP 1.0 spec for clients and proxies and Expires is per the HTTP 1.1 spec for clients and proxies. Other Cache-Control parameters are irrelevant if the above mentioned three are specified. The Last-Modified header as included in most other answers here is only if you actually want to cache the request, so you don’t need to specify it at all.\nNote that when the page is served over HTTP and a header is present in both the HTTP response headers and the HTML meta tags, then the one specified in the response header will get precedence over the HTML meta tag. The HTML meta tag will only be used when the page is viewed from local disk file system. See also W3 HTML spec chapter 5.2.2. Take care with this when you don’t specify them programmatically, because the web server can namely include some default values. To verify the one and other, you can see/debug them using Firebug Net panel.\n","date":"21 August 2013","externalUrl":null,"permalink":"/no-caching-in-any-browser/","section":"Articles","summary":"I need to stop caching across all browsers of my website for security reasons. This has been driving me nuts over the past two weeks, as every method I try just keep allow some caching to be stored. Easiest way to check is by pressing the back key on the browsers window as the results should update.\n","title":"No Caching in any Browser","type":"articles"},{"content":"Background Note: Click the process for a larger version.\nWhen a bug is first created it is assigned a nominal story point value of 1. This value is intended to cover the investigation phase of the bug only (or a fix if it’s found to be a small issue). Having a story point value against the bug (even if it only covers investigation initially) means that we can allocate each bug into a sprint along with other backlog items and gives a window of time to investigate the problem. The outcome of this stage should be either: Bug resolved; should only occur with small bugs where the issue was found, fixed and re-tested within the allocated tasked hours Further investigation required; in which case the story-point value of the bug should be increased to indicate that the problem is very complex and was not able to even be progressed during the first pass through the stage Investigation completed; where the problem has been documented within the bug item and a number of tasks (with associated hours assigned) have been created which detail how to resolve the problem Bugs which have not progressed (e.g. outcome 2 in the list above) should be re-story-pointed and added back into the main backlog to progress through stage 1 again at a later date. Obviously bugs which have been resolved (outcome 1) can be marked as such and bugs which have been investigated and tasked (outcome 3) can be added back into the product backlog for assigning to a future sprint. Note: The important point to note about this phase is that it should be considered time-boxed based on what time is allocated to the tasks created for the bug at sprint planning – based on the default story point value and current velocity, this should be roughly around 3 hours total. Stage 2 – Fixing Note: Click the process for a larger version. Bugs which enter this stage should have already been through the first stage of investigation at least once and should have appropriate tasks against them which detail what needs to happen to resolve the problem. Since each bug should have been through the first stage of analysis, we should know enough at this stage to be confident in being able to both apply a fix and complete the associated tasks in the allocated sprint. ","date":"16 August 2013","externalUrl":null,"permalink":"/bug-process/","section":"Articles","summary":"Background Note: Click the process for a larger version.\nWhen a bug is first created it is assigned a nominal story point value of 1. This value is intended to cover the investigation phase of the bug only (or a fix if it’s found to be a small issue). Having a story point value against the bug (even if it only covers investigation initially) means that we can allocate each bug into a sprint along with other backlog items and gives a window of time to investigate the problem. The outcome of this stage should be either: Bug resolved; should only occur with small bugs where the issue was found, fixed and re-tested within the allocated tasked hours Further investigation required; in which case the story-point value of the bug should be increased to indicate that the problem is very complex and was not able to even be progressed during the first pass through the stage Investigation completed; where the problem has been documented within the bug item and a number of tasks (with associated hours assigned) have been created which detail how to resolve the problem Bugs which have not progressed (e.g. outcome 2 in the list above) should be re-story-pointed and added back into the main backlog to progress through stage 1 again at a later date. Obviously bugs which have been resolved (outcome 1) can be marked as such and bugs which have been investigated and tasked (outcome 3) can be added back into the product backlog for assigning to a future sprint. Note: The important point to note about this phase is that it should be considered time-boxed based on what time is allocated to the tasks created for the bug at sprint planning – based on the default story point value and current velocity, this should be roughly around 3 hours total. Stage 2 – Fixing Note: Click the process for a larger version. Bugs which enter this stage should have already been through the first stage of investigation at least once and should have appropriate tasks against them which detail what needs to happen to resolve the problem. Since each bug should have been through the first stage of analysis, we should know enough at this stage to be confident in being able to both apply a fix and complete the associated tasks in the allocated sprint. ","title":"Bug Process","type":"articles"},{"content":"Rules to organise the process of Checking in and out of TFS is vital for preserving the integrity of our solution. This list is by no means fool-proof and exhaustive and hence any suggestions are welcomed and encouraged. Before Checking In or Out: Consider getting latest. Check if someone else has already checked the file out. If so, inform that person. This to avoid duplicating activities. Checking out: You can check out a file either explicitly by right clicking and select Check-out or implicitly by typing into the file. Before Checking-Out, check that the file is already checked out by another person; if so, inform that user, this to avoid duplicating activities. Checking In: Before checking in make sure: The modified code compiles. The entire solution builds successfully. StyleCop rules implemented. Code reviewer is present. Add clear and concise description to what has been changed and why. Assign to Work Item(s) ID Code reviewer name entered. Never Auto-Merge; always merge manually. Check that all new files, or relevant assembly in the global Library folder, have been successfully added to TFS. Missing such files might trigger Build Server failure. After checking in keep an eye on the Build Server notification for successful build. At the end of the working day; if the coding is not successfully completed, you must “Shelf” the files within TFS. Make sure to regularly update relevant work items with progress and relevant comment. ","date":"16 August 2013","externalUrl":null,"permalink":"/tfs-standards-policy/","section":"Articles","summary":"Rules to organise the process of Checking in and out of TFS is vital for preserving the integrity of our solution. This list is by no means fool-proof and exhaustive and hence any suggestions are welcomed and encouraged. Before Checking In or Out: Consider getting latest. Check if someone else has already checked the file out. If so, inform that person. This to avoid duplicating activities. Checking out: You can check out a file either explicitly by right clicking and select Check-out or implicitly by typing into the file. Before Checking-Out, check that the file is already checked out by another person; if so, inform that user, this to avoid duplicating activities. Checking In: Before checking in make sure: The modified code compiles. The entire solution builds successfully. StyleCop rules implemented. Code reviewer is present. Add clear and concise description to what has been changed and why. Assign to Work Item(s) ID Code reviewer name entered. Never Auto-Merge; always merge manually. Check that all new files, or relevant assembly in the global Library folder, have been successfully added to TFS. Missing such files might trigger Build Server failure. After checking in keep an eye on the Build Server notification for successful build. At the end of the working day; if the coding is not successfully completed, you must “Shelf” the files within TFS. Make sure to regularly update relevant work items with progress and relevant comment. ","title":"TFS Standards Policy","type":"articles"},{"content":"The singleton pattern is used in almost all modern day programming languages, so why do I keep finding it written incorrectly in so many applications, so lets start with the right way\npublic sealed class SimpleNoLockLazy { static readonly SimpleNoLockLazy instance = new SimpleNoLockLazy(); // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static SimpleNoLockLazy() { } SimpleNoLockLazy() { } public static SimpleNoLockLazy Instance { get { return instance; } } }\u0026lt;/pre\u0026gt; So why this implementation? The reason for using a Singleton is for performance in a multi-threaded environment and this pattern is not only simple, but it is the fastest. I have attached a benchmark application, which is based on Jon Skeet’s benchmark, but testing using a Parallel processes.\nBenchmark.zip (9.98 kb)\nI found Jon Skeet’s article very useful\n","date":"16 August 2013","externalUrl":null,"permalink":"/singleton-pattern-the-right-way/","section":"Articles","summary":"The singleton pattern is used in almost all modern day programming languages, so why do I keep finding it written incorrectly in so many applications, so lets start with the right way\npublic sealed class SimpleNoLockLazy { static readonly SimpleNoLockLazy instance = new SimpleNoLockLazy(); // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static SimpleNoLockLazy() { } SimpleNoLockLazy() { } public static SimpleNoLockLazy Instance { get { return instance; } } }\u003c/pre\u003e So why this implementation? The reason for using a Singleton is for performance in a multi-threaded environment and this pattern is not only simple, but it is the fastest. I have attached a benchmark application, which is based on Jon Skeet’s benchmark, but testing using a Parallel processes.\n","title":"Singleton Pattern the right way","type":"articles"},{"content":" First off, why would you want to perform validation in the WCF layer?\nAfter a vigorous PEN test, it was noted that the validation was mainly happening at the client browser and the application required validation to occur at the business logic layer, in our case the WCF layer.\nIn general, when working with an MVC/ASP.NET web application, you would typically want to do validation on the client-side as well as on the server side. Whilst the custom validation is simple enough, you’d have to duplicate it on the client and server, which is annoying – now you have two places to maintain a single validation routine.\nLets look at different validation options that will assist us in solving the issues over validation.\nThere are five validation approaches which you can prefer during validations. Each one has advantages and disadvantages over each other. Also, it is possible to apply multiple approaches at the same time. For example, you can implement self validation and data annotation attributes approaches at the same time, which gives you much flexibility.\nRule sets in configuration Validation block attributes Data annotation attributes Self-validation Validators created programmatically Rule sets in Configuration In this approach, we put our validation rules into the configuration file (web.config in ASP.NET and app.config in Windows applications). Here is an example showing how to define validation rules:\n\u0026lt;?xml version=\"1.0\" encoding=\"utf-8\" ?\u0026gt; \u0026lt;configuration\u0026gt; \u0026lt;configSections\u0026gt; \u0026lt;section name=\"validation\" type=\"Microsoft.Practices.EnterpriseLibrary. Validation.Configuration.ValidationSettings, Microsoft.Practices.EnterpriseLibrary.Validation, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" requirePermission=\"true\" /\u0026gt; \u0026lt;/configSections\u0026gt; \u0026lt;validation\u0026gt; \u0026lt;type name=\"ELValidation.Entities.BasicCustomer\" defaultRuleset=\"BasicCustomerValidationRules\" assemblyName=\"ELValidation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\"\u0026gt; \u0026lt;ruleset name=\"BasicCustomerValidationRules\"\u0026gt; \u0026lt;properties\u0026gt; \u0026lt;property name=\"CustomerNo\"\u0026gt; \u0026lt;validator type=\"Microsoft.Practices.EnterpriseLibrary. Validation.Validators.NotNullValidator, Microsoft.Practices.EnterpriseLibrary.Validation\" negated=\"false\" messageTemplate=\"Customer must have valid no\" tag=\"CustomerNo\" name=\"Not Null Validator\" /\u0026gt; \u0026lt;validator type=\"Microsoft.Practices.EnterpriseLibrary. Validation.Validators.StringLengthValidator, Microsoft.Practices.EnterpriseLibrary.Validation\" upperBound=\"5\" lowerBound=\"5\" lowerBoundType=\"Inclusive\" upperBoundType=\"Inclusive\" negated=\"false\" messageTemplate=\"Customer no must have {3} characters.\" tag=\"CustomerNo\" name=\"String Length Validator\" /\u0026gt; \u0026lt;validator type=\"Microsoft.Practices.EnterpriseLibrary. Validation.Validators.RegexValidator, Microsoft.Practices.EnterpriseLibrary.Validation\" pattern=\"[A-Z]{2}[0-9]{3}\" options=\"None\" patternResourceName=\"\" patternResourceType=\"\" messageTemplate=\"Customer no must be 2 capital letters and 3 numbers.\" messageTemplateResourceName=\"\" messageTemplateResourceType=\"\" tag=\"CustomerNo\" name=\"Regex Validator\" /\u0026gt; \u0026lt;/property\u0026gt; \u0026lt;/properties\u0026gt; \u0026lt;/ruleset\u0026gt; \u0026lt;/type\u0026gt; \u0026lt;/validation\u0026gt; \u0026lt;/configuration\u0026gt; Validation Block Attributes In this approach, we define our validations through the attributes defined in Enterprise Library validation block.\n[NotNullValidator(MessageTemplate = \"Customer must have valid no\")] [StringLengthValidator(5, RangeBoundaryType.Inclusive, 5, RangeBoundaryType.Inclusive, MessageTemplate = \"Customer no must have {3} characters.\")] [RegexValidator(\"[A-Z]{2}[0-9]{3}\", MessageTemplate = \"Customer no must be 2 capital letters and 3 numbers.\")] public string CustomerNo { get; set; } Message template is a good way to provide meaningful messages on failure with the flexibility to be replaced by Enterprise Library validation block for brackets.\nData Annotation Attributes In this approach, we define our validations through the attributes defined within System.ComponentModel.DataAnnotations assembly.\n[Required(ErrorMessage = \"Customer no can not be empty\")] [StringLength(5, ErrorMessage = \"Customer no must be 5 characters.\")] [RegularExpression(\"[A-Z]{2}[0-9]{3}\", ErrorMessage = \"Customer no must be 2 capital letters and 3 numbers.\")] public string CustomerNo { get; set; } This approach is widely used in conjunction with Entity Framework, MVC and ASP.NET validations.\nSelf-validation This approach gives much flexibility to us in order to create and execute complex validation rules.\nIn order to implement this approach, we first decorate HasSelfValidation attribute with the object type as shown in the following example:\n[HasSelfValidation] public class AttributeCustomer { … } Then, we write our validation logic by putting SelfValidation attribute on the top of the method which executes the validations.\n[SelfValidation] public void Validate(ValidationResults validationResults) { var age = DateTime.Now.Year - DateTime.Parse(BirthDate).Year; // Due to laws, only customers older than 18 can be registered // to system and allowed to order products if (age \u0026amp;lt; 18) { validationResults.AddResult( new ValidationResult(\u0026quot;Customer must be older than 18\u0026quot;, this, \u0026quot;BirthDate\u0026quot;, null, null)); } }\nValidators Created Programmatically This approach is different from the others because validation rules are created programmatically and executed independent of the type.\nFirst, we define our validation rules:\nValidator[] validators = new Validator[] { new NotNullValidator(false, \"Value can not be NULL.\"), new StringLengthValidator(5, RangeBoundaryType.Inclusive, 5, RangeBoundaryType.Inclusive, \"Value must be between {3} and {5} chars.\") }; Then, we add them into one of the composite validators depending on your preference.\nvar validator = new AndCompositeValidator(validators); In this example, we check Value to be tested… if it is not null and it has five exact characters.\nFinally, I want to mention about the validations against collections. Actually, it is similar to the validations for objects.\n// Initialize our object and set the values var customer = new AttributeCustomer(); FillCustomerInfo(customer);\n// Create a list of objects and add the objects to be tested to the list List\u0026lt;AttributeCustomer\u0026gt; customers = new List\u0026lt;AttributeCustomer\u0026gt;(); customers.Add(customer);\n// Initialize our validator by providing the type of objects in the list and validate them Validator cusValidator = new ObjectCollectionValidator(typeof(AttributeCustomer)); ValidationResults valResults = cusValidator.Validate(customers);\n// Show our validation results ShowResults(valResults);\nFirst thought was to use the MVC answer to validation – DataAnnotations, so why can’t we do this?\nWCF is technology for exposing services and it does it in interoperable way. Data contract exposed by the service is just create for data. It doesn’t matter how many fancy attributes you use on the contract or how many custom logic you put inside get and set methods of the property. On the client side you always see just the properties.\nThe reason for this is that once you expose the service it exposes all its contracts in interoperable way – service and operation contracts are described by WSDL and data contracts are described by XSD. XSD can describe only structure of data but no logic. The validation itself can be in some limited way be described in XSD but .NET XSD generator doesn’t do this. Once you add service reference to your WCF service the proxy generator will take WSDL and XSD as a source and create your classes again without all that attributes.\nIf you want to have client side validation you should in the first place implement that validation on the client side – it can be done by using buddy classes for partial classes used by WCF proxy. If you want to have a maintenance nightmare and you don’t want to use this way you must share assembly with your entities between your WCF client and WCF service and reuse those types when adding service reference. This will create tight coupling between your service and ASP.NET MVC application.\nWhat about Microsoft.Practices.EnterpriseLibrary.Validation.Validators? This is a possible solution to the WCF layer, but what this does not provide is a process to pass the validation back to the UI for JavaScript validation, which you get from DataAnnotations.\nIt may be worth using both the DataAnnotations and the Enterprise Library validation block together.\nOne question still to remain, is if the validation fails in the Services layer (WCF) how does the validation message get passed to the calling WCF client?\nIn general, when working with an MVC/ASP.NET web application, you would typically want to do validation on the client-side as well as on the server side. Whilst the custom validation is simple enough, you’d have to duplicate it on the client and server, which is annoying – now you have two places to maintain a single validation routine.\nSo what else can we use?\nFirst of all, do not throw Exceptions as a way of validating data – that’s a way too expensive operation, instead of graceful handling of invalid data.\nIf you would like to see some sample code take a look at Microsoft Enterprise Library 5.0 – Introduction to Validation Block by Ercan Anlama\nELValidation_src.zip (772.17 kb)\nWe’ve looked at all possible validation options, now the searching question is how do pass the validation over WCF to the WCF client for validation? to be continued……\n","date":"9 July 2013","externalUrl":null,"permalink":"/validation-from-wcf-layer-through-to-mvc/","section":"Articles","summary":" First off, why would you want to perform validation in the WCF layer?\nAfter a vigorous PEN test, it was noted that the validation was mainly happening at the client browser and the application required validation to occur at the business logic layer, in our case the WCF layer.\n","title":"Validation from WCF layer through to MVC","type":"articles"},{"content":"","date":"8 July 2013","externalUrl":null,"permalink":"/categories/iis8/","section":"Categories","summary":"","title":"IIS8","type":"categories"},{"content":"After a number of 500 errors coming up from IIS8 under Windows Server 2012, I final found the solution.\nThe solution was to go back to the Microsoft Server 2012 Dashboard and select the “Add Roles” feature. Scroll down to the root “Web Server (IIS)”, expand “Web Server”, expand “Application Development” and select “ASP.NET 3.5” and “ASP.NET 4.5” and “Install”.\nWhat confused me originally was I hadn’t expanded “Application Development”, but selected IIS and continued. On the next step, “Features”, “.NET Framework 4.5 Features” was selected by default so I selected “.NET Framework 3.5 Features” and thought all would be fine.\n","date":"8 July 2013","externalUrl":null,"permalink":"/mvc-running-on-iis8/","section":"Articles","summary":"After a number of 500 errors coming up from IIS8 under Windows Server 2012, I final found the solution.\nThe solution was to go back to the Microsoft Server 2012 Dashboard and select the “Add Roles” feature. Scroll down to the root “Web Server (IIS)”, expand “Web Server”, expand “Application Development” and select “ASP.NET 3.5” and “ASP.NET 4.5” and “Install”.\n","title":"MVC running on IIS8","type":"articles"},{"content":"Writing Effective Use Cases – by Alistair Cockburn.pdf (420.04 kb)\nUse Case Template v0.1.docx (302.38 kb)\n","date":"4 July 2013","externalUrl":null,"permalink":"/use-case-templates/","section":"Articles","summary":"Writing Effective Use Cases – by Alistair Cockburn.pdf (420.04 kb)\nUse Case Template v0.1.docx (302.38 kb)\n","title":"Use Case templates","type":"articles"},{"content":"There are many ways to validate if an e-mail address is right, and many wrong ways. The biggest wrong way is using a Regular expression, why? They are complex and there is not one that resolves this issue, you will always get an invalid e-mail address that passes through okay.\nSo what can we do? Why not use something that already works, something that someone else maintains, something we already have?\nLet’s take a look at the System.Net.Mail name space, it has MailAddress, and if you add a string that is an invalid e-mail address it fails eg:\nnew MailAddress(\"invalidemailaddress\"); This causes an exception to be thrown.\nThis mean you can use a single line of code to see if an e-mail is valid or not.\nLet’s make it more practical and generate a ValidationAttribute that validates an email address for any given field in a model, what we are after doing is something like this:\npublic class UserModel { [Required] public string name { get; set; } [Email] public string email { get; set; } }\u0026lt;/pre\u0026gt; To does this we just need to create an email attribute:\npublic class EmailAttribute : ValidationAttribute { protected override ValidationResult IsValid (object value, ValidationContext validationContext) { if (string.IsNullOrWhiteSpace(value?.ToString())) return ValidationResult.Success; try { new MailAddress(value.ToString()); } catch (Exception) { return new ValidationResult(\u0026quot;Please provide a valid email address.\u0026quot;); } return ValidationResult.Success; } }\u0026lt;/pre\u0026gt; So simple when you know how to do it.\n","date":"27 June 2013","externalUrl":null,"permalink":"/validating-an-e-mail-address-the-dataannotation-way/","section":"Articles","summary":"There are many ways to validate if an e-mail address is right, and many wrong ways. The biggest wrong way is using a Regular expression, why? They are complex and there is not one that resolves this issue, you will always get an invalid e-mail address that passes through okay.\n","title":"Validating an e-mail address the DataAnnotation way","type":"articles"},{"content":"It is quite an easy process to upload files from a web browser, but how do you know it is the correct type of document you are asking for?\nYou can check the file extenstion, but a hacker would just change the file type to another extension, so this is not a fail safe way of checking the file type being uploaded.\nAnother way which can check for the content of the file being uploaded and look for a signature.\nFirst we will need to hold the signature in a file type, so lets create an enum for them\npublic enum FileType { Gif = 7173, Jpg = 255216, Png = 13780, Bmp = 6677, TxtAspxAspSql = 239187, XlsDocPpt = 208207, Xml = 6063, Html = 6033, Js = 4742, XlsxZipPptxMmapZip = 8075, Rar = 8297, AccdbMdb = 01, ExeDll = 7790, Bat = 64101, Unknown } You’ll notice that some file types have the same signature so you need to be a little careful with these files.\nNow for the method that will return our file type:\nprotected FileType IsImageFile(HttpPostedFileBase file) { var fs = new FileStream(file.FileName, FileMode.Open, System.IO.FileAccess.Read); var br = new BinaryReader(fs); string fileclass; byte buffer; try { buffer = br.ReadByte(); fileclass = buffer.ToString(); buffer = br.ReadByte(); fileclass += buffer.ToString(); } catch { return FileType.Unknown; } finally { br.Close(); fs.Close(); } foreach (var type in Enum.GetValues(typeof(FileType))) { var l = (int)type; String[] fileType = {l.ToString()}; if (fileType.Any(t =\u0026amp;gt; fileclass == t)) { return (FileType)Enum.Parse(typeof(FileType), type.ToString()); } } return FileType.Unknown; }\u0026lt;/pre\u0026gt; That is it, all done\n","date":"25 June 2013","externalUrl":null,"permalink":"/determine-which-file-type-has-been-uploaded/","section":"Articles","summary":"It is quite an easy process to upload files from a web browser, but how do you know it is the correct type of document you are asking for?\nYou can check the file extenstion, but a hacker would just change the file type to another extension, so this is not a fail safe way of checking the file type being uploaded.\n","title":"Determine which file type has been uploaded","type":"articles"},{"content":"Have you ever opened a page for one of your websites and it lags for a while before it finally shows a page but then all of your following requests are quick? If you were to Google the problem you’d find that often it ends up having to do with IIS meeting an idle time limit and shuts down your site.\nKeep me Alive private static void _SetupRefreshJob() { //remove a previous job Action remove = HttpContext.Current.Cache[\u0026quot;Refresh\u0026quot;] as Action; if (remove is Action) { HttpContext.Current.Cache.Remove(\u0026quot;Refresh\u0026quot;); remove.EndInvoke(null); } //get the worker Action work = () =\u0026amp;gt; { while (true) { Thread.Sleep(60000); //TODO: Refresh Code (Explained in a moment) } }; work.BeginInvoke(null, null); //add this job to the cache HttpContext.Current.Cache.Add( \u0026quot;Refresh\u0026quot;, work, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, (s, o, r) =\u0026amp;gt; { _SetupRefreshJob(); } ); }\nIf we place this code in the Global.asax and call it when Application_Start() is raised, we can basically start a job that keeps our website alive. You could just as easily use a Thread to host the refresh method but for this example we simply used an Action delegate.\nOnce our application starts the refresh job is also started and is saved to the cache. In this example we’re using 60 seconds, but you can change this to be as often as you like.\nSo How Can We Keep It Fresh? So how about an example of some code we can use? Here is a simple example that could keep our website alive. Replace the //TODO: in the example above with something like the following.\nWebClient refresh = new WebClient(); try { refresh.UploadString(\"http://www.website.com/\", string.Empty); } catch (Exception ex) { //snip... } finally { refresh.Dispose(); } This snippet uses a WebClient to actually make an HTTP call to our website, thus keeping the site alive! We could do any number of things from this code like updating local data or get information from external resource. This can be used to keep our site alive and our content refreshed, even if we’re using a Hosted Environment!\nIt is worth nothing that might not actually need to do an HTTP call back to your website. It is possible that using any method will keep your website from being killed off (but I haven’t tested it yet so let me know what happens if you try it). This example, however, has been tested and works quite well with my provider.\nYou need to be careful that you don’t call a page with any Analytics attached, otherwise you’ll get false reading in your logs.\nOriginal article\n","date":"17 June 2013","externalUrl":null,"permalink":"/stay-alive-in-mvc/","section":"Articles","summary":"Have you ever opened a page for one of your websites and it lags for a while before it finally shows a page but then all of your following requests are quick? If you were to Google the problem you’d find that often it ends up having to do with IIS meeting an idle time limit and shuts down your site.\n","title":"Stay Alive in MVC","type":"articles"},{"content":"Is this possible?\nIt is possible to overload a method in WCF. However, when you want to expose overloaded methods as operations in a WCF contract, there is more to it than simply writing two or more methods with the same name.\nConsider the following example:\n[ServiceContract] public interface ICalendarService { [OperationContract] ScheduledEvent[] GetScheduledEvents(DateTime date); [OperationContract] ScheduledEvent[] GetScheduledEvents(DateTime start, DateTime end); }\nNow, try to actually implement this interface and host it as a WCF service. An InvalidOperationException will be raised when you invoke ServiceHost.Open. As far as the C# compiler is concerned, this is a completely legal piece of code. The interface contains two methods. The methods have the same name, but their signatures are unique since their parameters differ. The interface and methods are decorated with attributes. However, WCF doesn’t have any special hooks into the compiler. Consequently, the compiler doesn’t have any special knowledge about the attributes. It is simply going to emit their information in the assembly metadata.\nWhen WCF attempts to start the service, it essentially interrogates the metadata to generate a WSDL contract. WSDL is all about technology neutral, message based communication. It doesn’t support object-oriented concepts such as inheritance and overloading. (Actually, I think the earliest versions of WSDL allowed overloading to a certain extent, but it has since been removed in the newer versions.) So, WCF basically detects there are two methods with the same name and raises an exception to indicate this isn’t allowed even though the code compiled without any errors.\nRegardless, WCF still provides the ability to overload methods. This can be achieved by using the name property of the OperationContract attribute. By default, the name of the method will be used for the value of the name property. However, you can explicitly set the value of the name property to provide a unique value. Under the covers, WCF will use the value you supply as the name of the corresponding operation in the generated WSDL.\nHere is our previous example revised to use alias method names:\n[ServiceContract] public interface ICalendarService { [OperationContract(Name = \"GetScheduledEventsByDate\")] ScheduledEvent[] GetScheduledEvents(DateTime date); [OperationContract(Name = \u0026ldquo;GetScheduledEventsByDateRange\u0026rdquo;)] ScheduledEvent[] GetScheduledEvents(DateTime start, DateTime end); }\nYou may be wondering how the method will appear to the consumer of the service. Will it appear as two different names (based on the the alias) or as overloaded methods with the same name? This will depend upon the proxy class used by your client. If you use the proxy class that is automatically generated by svcutility.exe, the alias method names will be used. However, you can manually edit the generated proxy class to achieve the appearance of overloaded methods on the client as well. This can be accomplished by applying the same attributes to the methods defined in the interface that is used by the proxy class.\nOriginal article from Jeff Barnes\n","date":"11 June 2013","externalUrl":null,"permalink":"/overloading-methods-in-wcf/","section":"Articles","summary":"Is this possible?\nIt is possible to overload a method in WCF. However, when you want to expose overloaded methods as operations in a WCF contract, there is more to it than simply writing two or more methods with the same name.\n","title":"Overloading Methods in WCF","type":"articles"},{"content":"Write up the following post\nhttp://www.troyhunt.com/2012/01/aspnet-session-hijacking-with-google.html\n","date":"16 May 2013","externalUrl":null,"permalink":"/internal-error-messages-warning/","section":"Articles","summary":"Write up the following post\nhttp://www.troyhunt.com/2012/01/aspnet-session-hijacking-with-google.html\n","title":"Internal error messages warning","type":"articles"},{"content":"Cross Site Attacks (XSS) what is that all about? “Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications. XSS enables attackers to inject client-side script into Web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same origin policy. Cross-site scripting carried out on websites accounted for roughly 84% of all security vulnerabilities documented by Symantec as of 2007. Their effect may range from a petty nuisance to a significant security risk, depending on the sensitivity of the data handled by the vulnerable site and the nature of any security mitigation implemented by the site’s owner.” All user’s inputs can be a back door for attacker to attack your site. User’s inputs that we will categorize as un-trusted inputs are : Incoming URLs including Request.QueryString[] values Form post data (Request.Form[] values including values from hidden fields and disabled fields) Cookies Data in HTTP Headers (such as Request.UserAgent and Request.UrlReferrer). Your site could be attacked by altering the query string, form values, or cookies data. The solution is not to prevent request manipulation but to check that each request is a legal request for the logged-in visitor. Cross-Site Scripting and HTML Injection If an attacker can get our site to return some javascript to our visitors, then the attacker’s script can take control of our visitors’ browsing session and by this the attackers can collect the personal information (passwords, credit card details) of our visitors. There are two main ways an attacker follow to get this: Persistently: by entering formed malicious input into some feature and hoping we will store it into our database and then issue it back to other visitors. Non-persistently or Passively : by finding a way of sending malicious data in a request to our application and having our application echo that data back in it is response. The attacker then finds a way to trick a victim into making such a request. Razor HTML Encoding The Razor view engine helps protect us against XSS attacks by encoding any data that we refer to using the @ tag to make it safe to display as HTML. This means when we request an URL with a javascript code as a query string, Razor processes the query string value and replaces the special characters and rendering javascript code as a simple text. Razor view engine treats the contents of MvcHtmlString objects as if they were encoded, even when that is not the case. We can use Html.Raw helper method to include our HTML into the web page without it being encoded.\nRequest Validation The goal of request validation is to stop potentially dangerous data ever reaching the application. If the user tries to submit data that looks like it might be HTML, Then ASP.Net throws an exception. This happens before the request is passed to the MVC Framework, so our application never receives the data the user has sent. But the problem with Request Validation is that it rejects any data even slightly resembling an HTML tag, and this can include valid data. In ASP.Net MVC Framework, request validation is enabled by default. You can disable it by decorate your controller/action method by ValidateInput attribute and passing false to it. If you decorate the controller with it, that means you enabled/disabled request validation for all action methods within this controller (of course not recommended). If you decorate the action method by that attribute, that means you enabled/disabled request validation for all posted data/model properties. Also you can disable request validation for a specific property by decorate it with AllowHtml attribute. JavaScript String Encoding and XSS So what if we want to accept javascript code from the user, i.e post a question on stackoverflow. of course we don’t want to refuse it or disable request validation totally. Fortunately, the Ajax helper class has method called JavaScriptStringEncode, which encodes a string so that it safe to display and escapes characters so that JavaScript will understand it. In such case we have to use Html.Raw method around the result generated by the Ajax helper method. If we don’t do this, then Razor HTML encodes the result, and we are back where we started. Session Hijacking:\nASP.Net identifies users by session ID cookie which called ASP.Net_SessionId by default, and if we use Forms Authentication, then a second cookie is used called /AUTH. If an attacker can obtain these cookies, then they can include them in a request to our server and impersonate one of our users. The browser by default preventing the javascript from a site to access cookies of another site. But if the attacker has been able to inject a script into one of our pages, then the browser believes that the script is part of our application and grands access to the session cookies. We can protect our site by keeping a record of each client IP address when a session starts, we can deny any requests that originate from a different IP. But you should avoid this technique when you deal with the public internet.\nWe can mark a cookie with the HttpOnly flag, and the browser will hide its existence from javascript but will continue to send it via all HTTP requests. By default ASP.Net marks ASP.Net_SessionId and /AUTH as HttpOnly. Of course you can apply HttpOnly to your session cookies when you create them.\nCross-Site Request Forgery (CSRF): To save me repeating myself talk a look at this post Preventing Cross Site Request Forgery Build your MVC application securely Don’t write any public method inside a controller class that will not be an action method. By default any public method is an action method, other methods should be wrote in model section. If you have to write a method that will not be an action, make sure it will be private or make it public but you must decorate it with NonAction attribute. Prevent Model Binding to change sensitive data by using Bind attribute to set up white/black list that restrict which properties model binding is allowed/not allowed to populate. ","date":"15 May 2013","externalUrl":null,"permalink":"/cross-site-attacks-xss/","section":"Articles","summary":"Cross Site Attacks (XSS) what is that all about? “Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications. XSS enables attackers to inject client-side script into Web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same origin policy. Cross-site scripting carried out on websites accounted for roughly 84% of all security vulnerabilities documented by Symantec as of 2007. Their effect may range from a petty nuisance to a significant security risk, depending on the sensitivity of the data handled by the vulnerable site and the nature of any security mitigation implemented by the site’s owner.” All user’s inputs can be a back door for attacker to attack your site. User’s inputs that we will categorize as un-trusted inputs are : Incoming URLs including Request.QueryString[] values Form post data (Request.Form[] values including values from hidden fields and disabled fields) Cookies Data in HTTP Headers (such as Request.UserAgent and Request.UrlReferrer). Your site could be attacked by altering the query string, form values, or cookies data. The solution is not to prevent request manipulation but to check that each request is a legal request for the logged-in visitor. Cross-Site Scripting and HTML Injection If an attacker can get our site to return some javascript to our visitors, then the attacker’s script can take control of our visitors’ browsing session and by this the attackers can collect the personal information (passwords, credit card details) of our visitors. There are two main ways an attacker follow to get this: Persistently: by entering formed malicious input into some feature and hoping we will store it into our database and then issue it back to other visitors. Non-persistently or Passively : by finding a way of sending malicious data in a request to our application and having our application echo that data back in it is response. The attacker then finds a way to trick a victim into making such a request. Razor HTML Encoding The Razor view engine helps protect us against XSS attacks by encoding any data that we refer to using the @ tag to make it safe to display as HTML. This means when we request an URL with a javascript code as a query string, Razor processes the query string value and replaces the special characters and rendering javascript code as a simple text. Razor view engine treats the contents of MvcHtmlString objects as if they were encoded, even when that is not the case. We can use Html.Raw helper method to include our HTML into the web page without it being encoded.\n","title":"Cross Site Attacks – XSS","type":"articles"},{"content":"What is Cross Site Request Forgery (CSRF)?\n“A CSRF attack forces a logged-on victim’s browser to send a pre-authenticated request to a vulnerable web application, which then forces the victim’s browser to perform a hostile action to the benefit of the attacker. CSRF can be as powerful as the web application that it attacks.”\nCross-site scripting (XSS) is widely regarded as one of the most used security issue on the web. Few developers pay much attention to another form of attack that’s equally destructive and potentially far easier to exploit. Your application can be vulnerable to cross-site request forgery (CSRF) attacks not because you the developer did something wrong (as in, failing to encode outputs leads to XSS), but simply because of how the whole Web is designed to work.\nHow CSRF works All web application platforms are potentially vulnerable to CSRF, but in this post we’ll focus on ASP.NET MVC. Imagine you have a controller class as follows:\npublic class UserProfileController : Controller { public ViewResult Edit() { return View(); } public ViewResult SubmitUpdate() { // Get the user's existing profile data (implementation omitted) ProfileData profile = GetLoggedInUserProfile(); // Update the user object profile.EmailAddress = Request.Form[\u0026quot;email\u0026quot;]; profile.FavoriteHobby = Request.Form[\u0026quot;hobby\u0026quot;]; SaveUserProfile(profile); ViewData[\u0026quot;message\u0026quot;] = \u0026quot;Your profile was updated.\u0026quot;; return View(); } }\nThis is all very normal. First, the visitor goes to Edit(), which renders some form to let them change their user profile details. Secondly, they post that form to SubmitUpdate(), which saves the changes to their profile record in the database. There’s no XSS vulnerability here. Everything’s fine, right? We implement this sort of thing all the time…\nUnfortunately, this innocent controller is an easy target for CSRF. Imagine that an attacker sets up the following HTML page and hosts it on some server of their own:\n\u0026lt;body onload=\"document.getElementById('fm1').submit()\"\u0026gt; \u0026lt;form id=\"fm1\" action=\"http://yoursite/UserProfile/SubmitUpdate\" method=\"post\"\u0026gt; \u0026lt;input name=\"email\" value=\"hacker@somewhere.evil\" /\u0026gt; \u0026lt;input name=\"hobby\" value=\"Defacing websites\" /\u0026gt; \u0026lt;/form\u0026gt; \u0026lt;/body\u0026gt; Next, they somehow persuade a victim to visit this page. When this HTML page loads, it submits a valid form post to /UserProfile/SubmitUpdate on your server.\nAssuming you’re using Windows authentication or some kind of cookie-based authentication system such as Forms Authentication, the automated form post will be processed within the victim’s established authentication context, and will successfully update the victim’s email address to something under the attacker’s control. All the attacker has to do now is use your “forgotten password” facility, and they’re taken control of the victim’s account.\nOf course, instead of changing an victim’s email address, they can perform any action that the victim can perform with a single POST request. For example, they might be able to grant administrative permissions to another account, or post something defamatory to a CMS.\nWays to stop CSRF There are two main ways to block CSRF:\nCheck that incoming requests have a Referer header referencing your domain. This will stop requests unwittingly submitted from a third-party domain. However, some people disable their browser’s Referer header for privacy reasons, and attackers can sometimes spoof that header if the victim has certain versions of Adobe Flash installed. This is a weak solution. Put a user-specific token as a hidden field in legitimate forms, and check that the right value was submitted. If, for example, this token is the user’s password, then a third-party can’t forge a valid form post, because they don’t know each user’s password. However, don’t expose the user’s password this way: Instead, it’s better to use some random value (such as a GUID) which you’ve stored in the visitor’s Session collection or into a Cookie. Using the AntiForgeryToken helpers The core ASP.NET MVC package includes a set of helpers that give you a means to detect and block CSRF using the “user-specific tokens” technique.\nTo use these helpers to protect a particular form, put an Html.AntiForgeryToken() into the form, e.g.,\n@using(Html.Form(\"UserProfile\", \"SubmitUpdate\")) { @Html.AntiForgeryToken() \u0026lt;!-- rest of form goes here --\u0026gt; } This will output something like the following:\n\u0026lt;form action=\"/UserProfile/SubmitUpdate\" method=\"post\"\u0026gt; \u0026lt;input name=\"__RequestVerificationToken\" type=\"hidden\" value=\"saTFWpkKN0BYazFtN6c4YbZAmsEwG0srqlUqqloi/fVgeV2ciIFVmelvzwRZpArs\" /\u0026gt; \u0026lt;!-- rest of form goes here --\u0026gt; \u0026lt;/form\u0026gt; At the same time, Html.AntiForgeryToken() will give the visitor a cookie called __RequestVerificationToken, with the same value as the random hidden value shown above.\nNext, to validate an incoming form post, add the [ValidateAntiForgeryToken] filter to your target action method. For example,\n[ValidateAntiForgeryToken] public ViewResult SubmitUpdate() { // ... etc } This is an authorization filter that checks that:\nThe incoming request has a cookie called __RequestVerificationToken The incoming request has a Request.Form entry called __RequestVerificationToken These cookie and Request.Form values match Assuming all is well, the request goes through as normal. But if not, boom!, there’s an authorization failure with message “A required anti-forgery token was not supplied or was invalid”.\nThis prevents CSRF because even if a potential victim has an __RequestVerificationToken cookie, an attacker can’t find out its value, so they can’t forge a valid form post with the same value in Request.Form. But legitimate users aren’t inconvenienced at all; the mechanism is totally silent\nAnti-CSRF and AJAX The simple solution for adding AJAX Cross-Site request forgery is to add the Request Verification Token to the data\nfunction CallAjax() { var data = { \"ajaxparameter \": 'hello moon' }; data.__RequestVerificationToken = $(\"input[name=__RequestVerificationToken]\").val(); $.ajax({ type: \"POST\", url: '@Url.Action(\"AjaxCall\")', dataType: \"json\", data: JSON.stringify(data), success: function () { alert('Ajax call succesful'); } }); return false; } this can also be done via the $ajaxSetup\n$.ajaxSetup({ global: true, beforeSend: function (xhr, settings) { if (settings.data != \"\") { settings.data += '\u0026amp;'; } settings.data += '__RequestVerificationToken=' + $(\"input[name=__RequestVerificationToken]\").val(); } }); this then leaves the AJAX call as you would normally find it\nfunction CallAjax() { var data = { \"ajaxparameter \": 'hello moon' }; $.ajax({ type: \"POST\", url: '@Url.Action(\"AjaxCall\")', dataType: \"json\", data: JSON.stringify(data), success: function () { alert('Ajax call succesful'); } }); return false; } The form token can be a problem for AJAX requests, because an AJAX request might send JSON data, not HTML form data. One solution is to send the tokens in a custom HTTP header. The following code uses Razor syntax to generate the tokens, and then adds the tokens to an AJAX request. The tokens are generated at the server by calling AntiForgery.GetTokens.\n\u0026lt;script\u0026gt; @functions{ public string TokenHeaderValue() { string cookieToken, formToken; AntiForgery.GetTokens(null, out cookieToken, out formToken); return cookieToken + \":\" + formToken; } } $.ajax(\u0026quot;api/values\u0026quot;, { type: \u0026quot;post\u0026quot;, contentType: \u0026quot;application/json\u0026quot;, data: { }, // JSON data goes here dataType: \u0026quot;json\u0026quot;, headers: { 'RequestVerificationToken': '@TokenHeaderValue()' } }); \u0026lt;/script\u0026gt;\nWhen you process the request, extract the tokens from the request header. Then call the AntiForgery.Validate method to validate the tokens. The Validate method throws an exception if the tokens are not valid.\nvoid ValidateRequestHeader(HttpRequestMessage request) { string cookieToken = \"\"; string formToken = \"\"; IEnumerable\u0026amp;lt;string\u0026amp;gt; tokenHeaders; if (request.Headers.TryGetValues(\u0026quot;RequestVerificationToken\u0026quot;, out tokenHeaders)) { string[] tokens = tokenHeaders.First().Split(':'); if (tokens.Length == 2) { cookieToken = tokens[0].Trim(); formToken = tokens[1].Trim(); } } AntiForgery.Validate(cookieToken, formToken); }\nUsing salt Salt? What? In case you want to protect multiple forms in your application independently of each other, you can use a “salt” value when you call Html.AntiForgeryToken(), e.g.,\n@Html.AntiForgeryToken(\"someArbitraryString\") … and also in [ValidateAntiForgeryToken], e.g.,\n[ValidateAntiForgeryToken(Salt=\"someArbitraryString\")] public ViewResult SubmitUpdate() { // ... etc } Salt is just an arbitrary string. A different salt value means a different anti-forgery token will be generated. This means that even if an attacker manages to get hold of a valid token somehow, they can’t reuse it in other parts of the application where a different salt value is required\nLoad balancing Will different web servers in a load balanced configuration create the same token in the HTML forms?\nIf all machines across the farm share the same \u0026lt;machineKey\u0026gt;, everything will work. There are lots of resources on how to set this. There’s also a tutorial on MSDN.\nNote that the name \u0026lt;machineKey\u0026gt; is a bit misleading, since this is actually set per-application in ~/Web.config. So set the \u0026lt;machineKey\u0026gt; explicitly in your app’s Web.config, then deploy across your farm.\nLimitations of the Anti-Forgery helpers ASP.NET MVC’s anti-CSRF helpers work very nicely, but you should be aware of a few limitations:\nAll legitimate visitors must accept cookies (otherwise, [ValidateAntiForgeryToken] will deny their form posts). Arguably this isn’t a limitation, because unless visitors allow cookies, you probably don’t have anything to protect anyway. It only works with POST requests, not GET requests. Arguably this isn’t a limitation, because under the normal HTTP conventions, you shouldn’t be using GET requests for anything other than read-only operations. It’s easily bypassed if you have any XSS holes on your domain. An XSS hole would allow an attacker to read a victim’s anti-forgery token value, then use it to forge valid posts. So, don’t have XSS holes! It relies on the potential victim’s browser implementing cross-domain boundaries solidly. Browsers are supposed to stop foreign domains from reading your app’s response text and cookies, and are supposed to stop foreign domains from writing cookies to your domain. If an attacker manages to find a way around this, they can bypass [ValidateAntiForgeryToken]. Of course that’s not supposed to be possible. For the most part, modern browsers block this line of attack. Links\nThe Open Web Application Security Project\nThe orginal article was produced by Steven Sanderson:\nPrevent Cross-Site Request Forgery (CSRF) using ASP.NET MVC’s AntiForgeryToken() helper\nSource for this article\nCrossSiteRequestForgery.zip (3.21 mb)\n","date":"15 May 2013","externalUrl":null,"permalink":"/preventing-cross-site-request-forgery/","section":"Articles","summary":"What is Cross Site Request Forgery (CSRF)?\n“A CSRF attack forces a logged-on victim’s browser to send a pre-authenticated request to a vulnerable web application, which then forces the victim’s browser to perform a hostile action to the benefit of the attacker. CSRF can be as powerful as the web application that it attacks.”\n","title":"Preventing Cross Site Request Forgery","type":"articles"},{"content":"Following the TDD approach when you are working with MVC it is quite easy to produce Unit Tests that are based on the MVC Controllers, with more and more business logic appearing in the User Interface by using libraries such as jQuery it is becoming more important to perform Unit Testing on JavaScript.\nWhat options are available today, more importantly what are the pros and cons of each solution?\nJsUnit Pros\ncan be invoked from an ant build file\nlaunches browser to run the tests\nEclipse plug-in\nCons\nlaunches browser to run the tests\nDoes not support js file to write the unit test code: it has to be embedded inside an html file\nit has not been updated for a few years\nNotes:\nThere is a JsUnit (2).\nAn ‘ant’ is an open source build tool; “Ant” because it is a little thing that can build big things.\nRhinoUnit Pros\nant driven\nsupports js file\nvery simple to use\nCons\nSimulation of JavaScript engine: not advanced enough to support all coding types\ncrosscheck Pros\nCan be invoked from ant build file\nSimulates real browser behaviour\nCons\nSimulation of JavaScript engine from a limited number of browser versions\nNo activity for 2 years: it does not support Firefox versions 2.x nor 3.x\njsspec Pros\nRuns on actual browser\nCons\nJavaScript only framework: cannot be called from ant build file\njspec Pros\nRuns on actual browser\nCons\nDoes not seem to support all code types\nJavaScript only framework: cannot be called from ant build file,\nScrew.unit Pros\nRuns on actual browser\nCons\nJavaScript only framework: cannot be called from ant build file\nJSTest Pros\nCan be intergrated with most testing frameworks, such as MSTest, NUnit, xUnit etc\nant build supported\nSimple to install, only requires a single dll\nBrowserless\nCan be installed using NuGet\nSmall overhead of 56k\nCons\nNot very active on CodePlex, with only 51 downloads\nReference directly to the js files, so if the js files are moved all the tests need to be updated\nI know there are many many more and this is just a cross sample of JavaScript testing libraries, but I think I may have found the crown jewels for TDD.\nIt looks like JSTest is, not only the only choice we have, it is the simplest and best approach to JavaScript Unit Testing, but why has it only had 51 downloads? Have I found a hidden gem or a monster waiting to bite me?\nJSTest does provide an easy way to apply the Test-Driven Development (TDD) process\nFor an example to use it check out Unit Testing JavaScript with MSTest and JSTest.Net by Shawn Sweeney, I have created a sample MVC application showing it working.\nJSTestMVCExample.zip (2.67 mb)\nConclusion, I do think we now have the tools to be fully “TDD” compliant.\nJSTest.zip (16.80 kb)\n","date":"3 May 2013","externalUrl":null,"permalink":"/how-to-perform-javascript-unit-testing/","section":"Articles","summary":"Following the TDD approach when you are working with MVC it is quite easy to produce Unit Tests that are based on the MVC Controllers, with more and more business logic appearing in the User Interface by using libraries such as jQuery it is becoming more important to perform Unit Testing on JavaScript.\n","title":"How to perform JavaScript Unit Testing","type":"articles"},{"content":"TalentCubed.zip (3.34 mb)\n","date":"2 May 2013","externalUrl":null,"permalink":"/files/","section":"Articles","summary":"TalentCubed.zip (3.34 mb)\n","title":"files","type":"articles"},{"content":"Using the TDD approach in an MVC application, I was wondering how can you ensure that only certain roles have access to the controller. Why should we test for this? Because this is a clearly defined business rule and all business rules need to have Unit Tests where possible.\nThis is the code, which is quite simple\n[Authorize(Roles = \"Administrators\")] public class AdminController : Controller What we need to ensure is that a developer does not come along and add more roles or take away the Administrators roles.\nWe can do this using a Test and going through the Controller using reflection, like this:\n[TestMethod] public void AdminControllerShouldOnlyAvailableToAdministrators() { // Arrange var attributes = typeof(AdminController).GetCustomAttributes(true).ToList(); var countNonAdministrator = 0; var countAdministrator = 0; // Act foreach (var attribute in attributes.Where(attribute =\u0026amp;gt; attribute.GetType() == typeof(AuthorizeAttribute)).Cast\u0026amp;lt;AuthorizeAttribute\u0026amp;gt;()) { countNonAdministrator = attribute.Roles.Split(',').ToList().Count(role =\u0026amp;gt; role.ToString() != \u0026quot;Administrator\u0026quot;); } foreach (var attribute in attributes.Where(attribute =\u0026amp;gt; attribute.GetType() == typeof(AuthorizeAttribute)).Cast\u0026amp;lt;AuthorizeAttribute\u0026amp;gt;()) { countAdministrator = attribute.Roles.Split(',').ToList().Count(role =\u0026amp;gt; role.ToString() == \u0026quot;Administrator\u0026quot;); } // Assert Assert.IsTrue(countNonAdministrator == 0, \u0026quot;Administrators are only allowed to be authorised to use this controller\u0026quot;); Assert.IsTrue(countAdministrator == 1, \u0026quot;You must only have Administrators to be authorised to use this controller\u0026quot;); }\u0026lt;/pre\u0026gt; ","date":"30 April 2013","externalUrl":null,"permalink":"/how-to-test-only-certain-roles-should-have-access-to-a-controller-in-mvc/","section":"Articles","summary":"Using the TDD approach in an MVC application, I was wondering how can you ensure that only certain roles have access to the controller. Why should we test for this? Because this is a clearly defined business rule and all business rules need to have Unit Tests where possible.\n","title":"How to test “Only certain roles should have access to a controller” in MVC","type":"articles"},{"content":"Team Foundation Server provides the ultimate flexibility in terms of how you arrange our data. Because it simply versions directories and files, and because it describes no particular meaning to any of those objects, you may arrange the data in your repository in any way that we choose. Unfortunately, this flexibility also means that it’s easy to find yourself “lost without a roadmap” as you attempt to navigate different Team Foundation Server project repositories that may carry completely different and unpredictable arrangements of the data within them.\nTo counteract this confusion, you can using a repository layout convention (established long ago) in which a handful of strategically named Team Foundation Server repository directories convey valuable meaning about the data they hold. Most projects have a recognizable “main line”, or trunk, of development; some branches, which are divergent copies of development lines. So we first recommend that each project have a recognizable project root in the repository, a directory under which all of the versioned information for that project—and only that project—lives. Secondly, I suggest that each project root contain a trunk subdirectory for the main development line, a branches subdirectory in which specific branches (or collections of branches) will be created.\nIn our case branches will contain the developers name followed by the TFS task item they are working on. This makes it very clear at any time who and what was required.\nTrunk would be the main body of development, originating from the start of the project until the present.\nBranches will be a copy of code derived from a certain point in the trunk that is used for applying major changes to the code while preserving the integrity of the code in the trunk. If the major changes work according to plan, they are usually merged back into the trunk.\nShelve Pending Changes stores your code changes on the server but doesn’t commit them to the branch. Here are some reasons for using it:\nTo save changes but undo locally when I’m not ready to commit changes but I need to make an emergency bug fix on the same branch. To store code for code reviews prior to committing. Other people can check out or view your shelved changes. To store changes that are ready for committing when the changes aren’t approved yet. One thing to know about shelving changes: When you unshelve, you get the file as-is. If someone else has modified the file after your shelve, no merge happens. So I don’t recommend shelving changes long-term.\nHere are some examples of the structure\n$abc[1]\\src\\csp\\trunk\n$abc\\src\\csp\\branches\\David Jason\\3243\n$abc\\src\\csp\\branches\\David Jason\\3122\nThe repository main root has the following structure and shortened names, this is because Visual Studio has a 260 character name length restriction.\nsrc Source Code\ndep Deployments\nIf you are making a large Branch it is recommended that you plan you merge back to your trunk when you branch, as the longer period of time the Branch is separated from the Trunk the more work is going to be required to merge the two back together. As a rule of thumb one week is acceptable where as one month is much too long and will result in a lot of merge conflicts. If the branch is out of the main trunk for more than a month then before the code is merged back to the main trunk full testing of the source will be required, both unit tests and system integration testing which will require to be signed off by the test team that it passes full regression testing before the code is merged back to the main trunk.\nWith larger branches they can have their own trunk and branches while they are being worked on. If a sub trunk has been created then it is best practice to make sure a build is triggered on all checkins to this trunk to ensure that the code can be build successfully on the build server. It is important that the above paragraph on merging back is adhered to.\n[1] This is the your project level for the Repository; you will find many others as these are historic and should only be used for reference.\n","date":"25 April 2013","externalUrl":null,"permalink":"/the-repository-layout/","section":"Articles","summary":"Team Foundation Server provides the ultimate flexibility in terms of how you arrange our data. Because it simply versions directories and files, and because it describes no particular meaning to any of those objects, you may arrange the data in your repository in any way that we choose. Unfortunately, this flexibility also means that it’s easy to find yourself “lost without a roadmap” as you attempt to navigate different Team Foundation Server project repositories that may carry completely different and unpredictable arrangements of the data within them.\n","title":"The repository layout","type":"articles"},{"content":"I came across this smart little Profiler for SQL Express, or any version of SQL as it happens.\nMicrosoft SQL Server family includes free Express edition, that is fully functional, however has some disappointing limitations which prevent from using it in development process. One of them is absense of profiling tools, standard SQL profiler is not included. However, I came across this SQL Performance Profiler to use with the express edition for tuning your system.\nSQL Server Express Edition Profiler provides most of functionality standard profiler does, such as choosing events to profile, setting filters, etc. It is a small fee of about $5 for three licences, which is well worth the money.\nhttp://www.datawizard.com\n","date":"19 April 2013","externalUrl":null,"permalink":"/sql-performance-profiler-for-sql-express/","section":"Articles","summary":"I came across this smart little Profiler for SQL Express, or any version of SQL as it happens.\nMicrosoft SQL Server family includes free Express edition, that is fully functional, however has some disappointing limitations which prevent from using it in development process. One of them is absense of profiling tools, standard SQL profiler is not included. However, I came across this SQL Performance Profiler to use with the express edition for tuning your system.\n","title":"SQL Performance Profiler for SQL Express","type":"articles"},{"content":"Here is some neat SQL to allow you to search every table and every field in the database for a string\nCREATE TABLE myTable99 (TABLE_NAME sysname, COLUMN_NAME sysname, Occurs int) GO SET NOCOUNT ON\nDECLARE @SQL varchar(8000), @TABLE_NAME sysname, @COLUMN_NAME sysname, @Sargable varchar(80), @Count int\nSELECT @Sargable = \u0026lsquo;There are too many subscription products resulting from the supplied request data\u0026rsquo;\nDECLARE insaneCursor CURSOR FOR SELECT c.TABLE_NAME, c.COLUMN_NAME FROM INFORMATION_SCHEMA.Columns c INNER JOIN INFORMATION_SCHEMA.Tables t ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME WHERE c.DATA_TYPE IN (\u0026lsquo;char\u0026rsquo;,\u0026rsquo;nchar\u0026rsquo;,\u0026lsquo;varchar\u0026rsquo;,\u0026rsquo;nvarchar\u0026rsquo;,\u0026rsquo;text\u0026rsquo;,\u0026rsquo;ntext\u0026rsquo;) AND t.TABLE_TYPE = \u0026lsquo;BASE TABLE\u0026rsquo;\nOPEN insaneCursor\nFETCH NEXT FROM insaneCursor INTO @TABLE_NAME, @COLUMN_NAME\nWHILE @@FETCH_STATUS = 0 BEGIN SELECT @SQL = \u0026lsquo;INSERT INTO myTable99 (TABLE_NAME, COLUMN_NAME, Occurs) SELECT ' + \u0026rsquo;\u0026rsquo;\u0026rsquo;\u0026rsquo; + @TABLE_NAME + \u0026rsquo;\u0026rsquo;\u0026rsquo;\u0026rsquo; + \u0026lsquo;,\u0026rsquo; + \u0026rsquo;\u0026rsquo;\u0026rsquo;\u0026rsquo; + @COLUMN_NAME + \u0026rsquo;\u0026rsquo;\u0026rsquo;\u0026rsquo; + \u0026lsquo;,\u0026rsquo; + \u0026lsquo;COUNT(*) FROM [\u0026rsquo; + @TABLE_NAME\n+ \u0026lsquo;] WHERE [\u0026rsquo; + @COLUMN_NAME + \u0026lsquo;] Like ' + \u0026lsquo;\u0026rsquo;\u0026rsquo;\u0026rsquo;+ \u0026lsquo;%\u0026rsquo; + @Sargable + \u0026lsquo;%\u0026rsquo; + \u0026rsquo;\u0026rsquo;\u0026rsquo;\u0026rsquo; \u0026ndash;SELECT @SQL EXEC(@SQL) IF @@ERROR \u0026lt;\u0026gt; 0 BEGIN SELECT @SQL SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = @TABLE_NAME GOTO Error END FETCH NEXT FROM insaneCursor INTO @TABLE_NAME, @COLUMN_NAME END\nSELECT * FROM myTable99 WHERE Occurs \u0026lt;\u0026gt; 0\nError: CLOSE insaneCursor DEALLOCATE insaneCursor\nGO\nDROP TABLE myTable99 GO\nSET NOCOUNT OFF\n","date":"15 March 2013","externalUrl":null,"permalink":"/search-every-sql-table-for-a-string/","section":"Articles","summary":"Here is some neat SQL to allow you to search every table and every field in the database for a string\nCREATE TABLE myTable99 (TABLE_NAME sysname, COLUMN_NAME sysname, Occurs int) GO SET NOCOUNT ON\nDECLARE @SQL varchar(8000), @TABLE_NAME sysname, @COLUMN_NAME sysname, @Sargable varchar(80), @Count int\nSELECT @Sargable = ‘There are too many subscription products resulting from the supplied request data’\nDECLARE insaneCursor CURSOR FOR SELECT c.TABLE_NAME, c.COLUMN_NAME FROM INFORMATION_SCHEMA.Columns c INNER JOIN INFORMATION_SCHEMA.Tables t ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME WHERE c.DATA_TYPE IN (‘char’,’nchar’,‘varchar’,’nvarchar’,’text’,’ntext’) AND t.TABLE_TYPE = ‘BASE TABLE’\nOPEN insaneCursor\nFETCH NEXT FROM insaneCursor INTO @TABLE_NAME, @COLUMN_NAME\nWHILE @@FETCH_STATUS = 0 BEGIN SELECT @SQL = ‘INSERT INTO myTable99 (TABLE_NAME, COLUMN_NAME, Occurs) SELECT ' + ’’’’ + @TABLE_NAME + ’’’’ + ‘,’ + ’’’’ + @COLUMN_NAME + ’’’’ + ‘,’ + ‘COUNT(*) FROM [’ + @TABLE_NAME\n+ ‘] WHERE [’ + @COLUMN_NAME + ‘] Like ' + ‘’’’+ ‘%’ + @Sargable + ‘%’ + ’’’’ –SELECT @SQL EXEC(@SQL) IF @@ERROR \u003c\u003e 0 BEGIN SELECT @SQL SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = @TABLE_NAME GOTO Error END FETCH NEXT FROM insaneCursor INTO @TABLE_NAME, @COLUMN_NAME END\nSELECT * FROM myTable99 WHERE Occurs \u003c\u003e 0\nError: CLOSE insaneCursor DEALLOCATE insaneCursor\nGO\nDROP TABLE myTable99 GO\nSET NOCOUNT OFF","title":"Search every SQL table for a string","type":"articles"},{"content":"The iPhone is the top smartphone, but some Android rivals like the Galaxy S III are very attractive, and they’re available in large sizes that the iPhone is not. Plus, they support cool technologies Apple doesn’t support.\nIf you’re ensconced in the Apple fold, you may believe you have to stay all-Apple. It turns out that you can bring Android largely into the Apple ecosystem.\nGetting iCloud email Apple’s iCloud sync and cloud storage service is one of iOS’s and OS X’s key attractions. But Apple keeps it in the family to encourage people to commit. However, you can access iCloud email from the standard Android Email app.\nThe key is to sign in using your iCloud account’s me.com address, not your icloud.com address. The incoming server is mail.me.com, and the outgoing server is smtp.me.com. SSL should be on.\nSyncing iCloud contacts and calendars iCloud’s auto-syncing contacts and calendars make it supereasy to keep your Mac, iPhone, and iPad up to date with each other. They even work with Windows — but not Android.\nThat is, unless you buy two utilities for £3.75 each from developer Marten Gajda: Smoothsync for Cloud Calendar and Smoothsync for Cloud Contacts. Both are available in the Google Play app store.\nSign in with your iCloud credentials, and your Android smartphone is now part of the iCloud family. Syncing documents Apple’s iCloud Documents feature in iOS — recently brought to OS X — can be very handy for keeping documents in sync across all devices you use to access or edit them. It’s an Apple-only feature for which there is no way to gain foreign access.\nBut that’s OK. iCloud Documents is quite limited, requiring the same app on each device to read a particular file type. Many apps in iOS aren’t on OS X, such as OS X’s TextEdit text editor, so iCloud Documents often can’t do the job.\nYou should use Google Drive or DropBox instead; many iOS apps support them natively, and they work on pretty much every mobile and desktop OS today.\nSyncing bookmarks and open URLs Apple’s Safari 6 in iOS, OS X, and Windows has a neat feature called iCloud Tabs that syncs the URLs of all open tabs to all other devices using Safari 6 tied to the same iCloud account. Bookmarks are also synced across these three OSes.\nAgain, there’s no way to open up Safari’s iCloud tabs and bookmark syncing to Android — so don’t use Safari. Google’s Chrome browser has a similar sync capability, and it’s available for Android, iOS, OS X, and Windows. (Firefox can also sync across platforms, but recently dropped its iOS sync app; it’s not an option if you’re using an iPad or other iOS device.)\nFind a lost or stolen smartphone Another great iCloud feature is Find My iPhone, which tracks your iOS and OS X devices, so you can find them on a map, send an alert (in case your phone is hidden under a blanket, for example) or message, and lock or wipe them if necessary. Just be sure you set the device so that a thief can’t turn off this feature. Again, Android can’t join in.\nBut there’s a comparable service called Lookout that lets you find, lock, or wipe a missing Android device from any browser. The basic version is free. However, be warned that it’s easy for a thief to disable it if he or she notices it’s installed.\nSyncing with iTunes One of Apple’s stickiest technologies is iTunes, which is both a library for your entertainment and store from which to get more of it. Google’s free Music Manager app for Windows and OS X syncs nonprotected music wirelessly to your Google Play account, but it must be streamed to your Android device.\nA better choice is the free DoubleTwist Player app, which syncs music, videos, and photos. Also, it can transfer these items from iOS device to Android. You need both the Android client and OS X or Windows client. Note that DoubleTwist is full of come-ons for in-app upgrades — annoyingly so. The $5 AirSync add-on is worthwhile, as it allows Wi-Fi syncing between your computer and Android device.\nStreaming to AirPlay Apple TV is an insidiously useful device, acting as a wireless bridge between Macs and iOS devices for screen mirroring and streaming of movies, music, podcasts, and photos. It too is an Apple-only technology.\nBut the £5 AirSync add-on utility for DoubleTwist lets you stream music and videos from an Android device to the Apple TV, just as if it were an iPhone or iPad. When it works, that is — I often could not get the AirTwist streaming icon to appear, and I never did figure out why.\nManaging book libraries iTunes includes the iBookstore, which lets you buy e-books for reading on the iBooks app on an iPad or iPhone, but iBooks doesn’t work on other devices, not even Macs. Except for the special Multi-Touch e-book format for the iPad, it’s not a great bookstore to use.\nAmazon.com’s Kindle app is a better choice, as it works on every major mobile and desktop platform, and its book selection is much larger than Apple’s.\nGetting directions Everyone knows by now that iOS 6’s Apple Maps has major flaws, and Apple has apologized for them. Plus, it provides voice navigation only on an iPhone 4S or iPhone 5. Compare that to Android, whose navigation app has worked well for several years on all Android devices.\nBut an even better option is the free Waze app; it’s available for both iOS and Android. It provides voice navigation on older iPhones, too.\nGetting apps It’s a cliché, but a true one: In iOS, there’s (very likely) an app for that. Android has a smaller app selection. But you’ll find that content apps and services apps (such as for banking, public transit, and airlines) are almost always available for Android if available for iOS. Ditto for basic utilities such as flashlights, social media, restaurant finders, and bar-code scanners.\nHave I gone to the dark side and switched over yet, no, I’m still running my iPhone 4s and Google Nexus 4 together. So I’m still sitting on the fence, perhaps the Samsung 4 will tip me over, we’ll just have to wait and see.\n","date":"15 March 2013","externalUrl":null,"permalink":"/switching-from-iphone-to-android/","section":"Articles","summary":"The iPhone is the top smartphone, but some Android rivals like the Galaxy S III are very attractive, and they’re available in large sizes that the iPhone is not. Plus, they support cool technologies Apple doesn’t support.\n","title":"Switching from iPhone to Android","type":"articles"},{"content":"When you are connecting via a remote connection to a server I find the Shut Down is far far to close to the log off, and if you hit the Shut Down by mistake it can be a devil to get the remote machine to power back up and may require someone to visit the machine to hit the power button.\nYou can disable the Shut Down button there is a group policy settings for this, start gpedit.msc on the machine or use a domain policy to configure User Configuration – Administrative templates – Start menu. See the setting “Remove and prevent access to the shut down, restart….”, change it to enabled.\nNo more shutting down by accident.\n","date":"12 March 2013","externalUrl":null,"permalink":"/disable-shut-down-on-your-server/","section":"Articles","summary":"When you are connecting via a remote connection to a server I find the Shut Down is far far to close to the log off, and if you hit the Shut Down by mistake it can be a devil to get the remote machine to power back up and may require someone to visit the machine to hit the power button.\n","title":"Disable Shut Down on your Server","type":"articles"},{"content":"When you develop web application you often have this scenario. Some people are testers, they are testing the application in dev all day, and they want always to test latest version. Moreover testers usually fills data into web application, so they want their data to be preserved between various deploy. If you simply clear all data in test database you will end with a lot of furious tester so do not even think to do this.\nIf a developer needs to change database schema, we need to automate not only the deploy of the web application, but we need also to sync test database with the latest changes. This is necessary so the test site can work with the new version, but old data is preserved for the happiness of the testers.\nThis is quite simple using TFS and Database project. The situation is this one\nWhen a developer does a check-in, the build server grabs the tip from TFS, then it runs the builds script and deploy the new version of the site in the test web server. At the same time test database gets updated with the latest database schema.\nNext we need the ability to automatically deploy changes to a specific database, this task is quite simple and you can find some details here in msdn, but we need to insert this command into the msbuild script. Here is the code:\n\u0026lt;Target Name=\"AfterDropBuild\"\u0026gt;\u0026lt;Message Text=\"Deploy of project database\" /\u0026gt; \u0026lt;MSBuild Projects=\"$(SolutionRoot)srcDbEditionNorthwindTestNorthwindTestNorthwindTest.dbproj\" Properties=\"OutDir=$(DropLocation)$(BuildNumber)debug; TargetDatabase=NorthwindCiTest; DefaultDataPath=C:Program FilesMicrosoft SQL ServerMSSQL.4MSSQLData; TargetConnectionString=Data Source=VM2003R2_1SQLTEST%3Buser=sa%3Bpwd=Pa$$w0rd; DeployToDatabase=true;\" Targets=\"Deploy\"/\u0026gt; \u0026lt;/Target\u0026gt; Original post from Ricci Gian Maria\nhttp://geekswithblogs.net/jakob/archive/2012/04/25/deploying-ssdt-projects-with-tfs-build/\n","date":"27 February 2013","externalUrl":null,"permalink":"/deploy-a-database-project-with-tfs-build/","section":"Articles","summary":"When you develop web application you often have this scenario. Some people are testers, they are testing the application in dev all day, and they want always to test latest version. Moreover testers usually fills data into web application, so they want their data to be preserved between various deploy. If you simply clear all data in test database you will end with a lot of furious tester so do not even think to do this.\nIf a developer needs to change database schema, we need to automate not only the deploy of the web application, but we need also to sync test database with the latest changes. This is necessary so the test site can work with the new version, but old data is preserved for the happiness of the testers.\nThis is quite simple using TFS and Database project. The situation is this one\n","title":"Deploy a database project with TFS Build","type":"articles"},{"content":"","date":"27 February 2013","externalUrl":null,"permalink":"/categories/visual-studio-2012/","section":"Categories","summary":"","title":"Visual Studio 2012","type":"categories"},{"content":"Three months in and my Visual Studio 2012 is running slow, I’ll even go as far as saying it is freezing up some times, so I loaded up SysInternals Process Monitor and set a filter on Visual Studio and to my complete and utter amazement I found PerfWatson running wild in the system\nPerfWatson is designed to drive performance improvements and make Visual Studio faster by automatically reporting back to Microsoft, this sounds great but it is just running crazy on my machine and I need to take it off.\nTo take it off you need to be in Visual Studio 2012, if you can get it loaded, then go to the Tools/Extensions and Updates sections and you’ll find Visual Studio PerfWatson installed, just uninstall and it will be gone.\nAnother area to clear out is the WebSiteCache, which Kevin Rintoul wrote about on his blog Slow Visual Studio Performance … Solved!, which can be found at:\nC:\\Users\\jQuery152010256510121984808_1361448287186jQuery152010612401940409233_1361449184152jQuery15207433351762976833_1361449212578??\\AppData\\Local\\Microsoft\\WebsiteCache\nIf you are using TFS with Visual Studio then another great tip from Nick on his blog post How to fix slow Visual Studio + TFS,\nEdit the Visual Studio config file found in C:\\Program Files (x86)\\Microsoft Visual Studio 11.0\\Common7\\IDE\\devenv.exe.config\nand locate the following line:\n\u0026lt;system.net\u0026gt; Right below (above settings, NOT under), insert the following line of code:\n\u0026lt;defaultProxy enabled=\"false\" /\u0026gt; Your visual studio should now be more responsive!\nAnyone else got any tips to increase the performance of Visual Studio 2012 are most welcome.\n","date":"21 February 2013","externalUrl":null,"permalink":"/visual-studio-2012-running-slow/","section":"Articles","summary":"Three months in and my Visual Studio 2012 is running slow, I’ll even go as far as saying it is freezing up some times, so I loaded up SysInternals Process Monitor and set a filter on Visual Studio and to my complete and utter amazement I found PerfWatson running wild in the system\n","title":"Visual Studio 2012 running slow","type":"articles"},{"content":"Need to know who is logged on to your SQL database ,here is a nice script that I got from Gary Dunne DECLARE @spid1 int = NULL /* server process id to check for locks */ DECLARE @spid2 int = NULL /* other process id to check for locks */ set nocount on /* ** Show the locks for both parameters. */ declare @objid int, @dbid int, @string Nvarchar(255)\nCREATE TABLE #locktable ( spid smallint ,loginname nvarchar(20) ,hostname nvarchar(30) ,dbid int ,dbname nvarchar(20) ,objId int ,ObjName nvarchar(128) ,IndId int ,Type nvarchar(4) ,Resource nvarchar(16) ,Mode nvarchar(8) ,Status nvarchar(5) )\nif @spid1 is not NULL begin INSERT #locktable ( spid ,loginname ,hostname ,dbid ,dbname ,objId ,ObjName ,IndId ,Type ,Resource ,Mode ,Status ) select convert (smallint, l.req_spid) \u0026ndash;,coalesce(substring (user_name(req_spid), 1, 20),\u0026rsquo;\u0026rsquo;) ,coalesce(substring (s.loginame, 1, 20),\u0026rsquo;\u0026rsquo;) ,coalesce(substring (s.hostname, 1, 30),\u0026rsquo;\u0026rsquo;) ,l.rsc_dbid ,substring (db_name(l.rsc_dbid), 1, 20) ,l.rsc_objid ,\u0026rsquo;' ,l.rsc_indid ,substring (v.name, 1, 4) ,substring (l.rsc_text, 1, 16) ,substring (u.name, 1, 8) ,substring (x.name, 1, 5) from master.dbo.syslockinfo l, master.dbo.spt_values v, master.dbo.spt_values x, master.dbo.spt_values u, master.dbo.sysprocesses s where l.rsc_type = v.number and v.type = \u0026lsquo;LR\u0026rsquo; and l.req_status = x.number and x.type = \u0026lsquo;LS\u0026rsquo; and l.req_mode + 1 = u.number and u.type = \u0026lsquo;L\u0026rsquo; and req_spid in (@spid1, @spid2) and req_spid = s.spid end /* ** No parameters, so show all the locks. */ else begin INSERT #locktable ( spid ,loginname ,hostname ,dbid ,dbname ,objId ,ObjName ,IndId ,Type ,Resource ,Mode ,Status ) select convert (smallint, l.req_spid) \u0026ndash;,coalesce(substring (user_name(req_spid), 1, 20),\u0026rsquo;\u0026rsquo;) ,coalesce(substring (s.loginame, 1, 20),\u0026rsquo;\u0026rsquo;) ,coalesce(substring (s.hostname, 1, 30),\u0026rsquo;\u0026rsquo;) ,l.rsc_dbid ,substring (db_name(l.rsc_dbid), 1, 20) ,l.rsc_objid ,\u0026rsquo;' ,l.rsc_indid ,substring (v.name, 1, 4) ,substring (l.rsc_text, 1, 16) ,substring (u.name, 1, 8) ,substring (x.name, 1, 5) from master.dbo.syslockinfo l, master.dbo.spt_values v, master.dbo.spt_values x, master.dbo.spt_values u, master.dbo.sysprocesses s where l.rsc_type = v.number and v.type = \u0026lsquo;LR\u0026rsquo; and l.req_status = x.number and x.type = \u0026lsquo;LS\u0026rsquo; and l.req_mode + 1 = u.number and u.type = \u0026lsquo;L\u0026rsquo; and req_spid = s.spid order by spID END DECLARE lock_cursor CURSOR FOR SELECT dbid, ObjId FROM #locktable WHERE Type =\u0026lsquo;TAB\u0026rsquo;\nOPEN lock_cursor FETCH NEXT FROM lock_cursor INTO @dbid, @ObjId WHILE @@FETCH_STATUS = 0 BEGIN SELECT @string = \u0026lsquo;USE \u0026rsquo; + db_name(@dbid) + char(13)\n+ \u0026lsquo;UPDATE #locktable SET ObjName = object_name(\u0026rsquo; + convert(varchar(32),@objId) + \u0026lsquo;) WHERE dbid = \u0026rsquo; + convert(varchar(32),@dbId) + \u0026rsquo; AND objid = \u0026rsquo; + convert(varchar(32),@objId)\nEXECUTE (@string) FETCH NEXT FROM lock_cursor INTO @dbid, @ObjId END CLOSE lock_cursor DEALLOCATE lock_cursor\nSELECT * FROM #locktable DROP TABLE #locktable\nsp_lock2.sql (3.44 kb)\n","date":"19 February 2013","externalUrl":null,"permalink":"/who-is-locking-my-sql-database/","section":"Articles","summary":"Need to know who is logged on to your SQL database ,here is a nice script that I got from Gary Dunne DECLARE @spid1 int = NULL /* server process id to check for locks */ DECLARE @spid2 int = NULL /* other process id to check for locks */ set nocount on /* ** Show the locks for both parameters. */ declare @objid int, @dbid int, @string Nvarchar(255)\nCREATE TABLE #locktable ( spid smallint ,loginname nvarchar(20) ,hostname nvarchar(30) ,dbid int ,dbname nvarchar(20) ,objId int ,ObjName nvarchar(128) ,IndId int ,Type nvarchar(4) ,Resource nvarchar(16) ,Mode nvarchar(8) ,Status nvarchar(5) )\nif @spid1 is not NULL begin INSERT #locktable ( spid ,loginname ,hostname ,dbid ,dbname ,objId ,ObjName ,IndId ,Type ,Resource ,Mode ,Status ) select convert (smallint, l.req_spid) –,coalesce(substring (user_name(req_spid), 1, 20),’’) ,coalesce(substring (s.loginame, 1, 20),’’) ,coalesce(substring (s.hostname, 1, 30),’’) ,l.rsc_dbid ,substring (db_name(l.rsc_dbid), 1, 20) ,l.rsc_objid ,’' ,l.rsc_indid ,substring (v.name, 1, 4) ,substring (l.rsc_text, 1, 16) ,substring (u.name, 1, 8) ,substring (x.name, 1, 5) from master.dbo.syslockinfo l, master.dbo.spt_values v, master.dbo.spt_values x, master.dbo.spt_values u, master.dbo.sysprocesses s where l.rsc_type = v.number and v.type = ‘LR’ and l.req_status = x.number and x.type = ‘LS’ and l.req_mode + 1 = u.number and u.type = ‘L’ and req_spid in (@spid1, @spid2) and req_spid = s.spid end /* ** No parameters, so show all the locks. */ else begin INSERT #locktable ( spid ,loginname ,hostname ,dbid ,dbname ,objId ,ObjName ,IndId ,Type ,Resource ,Mode ,Status ) select convert (smallint, l.req_spid) –,coalesce(substring (user_name(req_spid), 1, 20),’’) ,coalesce(substring (s.loginame, 1, 20),’’) ,coalesce(substring (s.hostname, 1, 30),’’) ,l.rsc_dbid ,substring (db_name(l.rsc_dbid), 1, 20) ,l.rsc_objid ,’' ,l.rsc_indid ,substring (v.name, 1, 4) ,substring (l.rsc_text, 1, 16) ,substring (u.name, 1, 8) ,substring (x.name, 1, 5) from master.dbo.syslockinfo l, master.dbo.spt_values v, master.dbo.spt_values x, master.dbo.spt_values u, master.dbo.sysprocesses s where l.rsc_type = v.number and v.type = ‘LR’ and l.req_status = x.number and x.type = ‘LS’ and l.req_mode + 1 = u.number and u.type = ‘L’ and req_spid = s.spid order by spID END DECLARE lock_cursor CURSOR FOR SELECT dbid, ObjId FROM #locktable WHERE Type =‘TAB’\nOPEN lock_cursor FETCH NEXT FROM lock_cursor INTO @dbid, @ObjId WHILE @@FETCH_STATUS = 0 BEGIN SELECT @string = ‘USE ’ + db_name(@dbid) + char(13)\n+ ‘UPDATE #locktable SET ObjName = object_name(’ + convert(varchar(32),@objId) + ‘) WHERE dbid = ’ + convert(varchar(32),@dbId) + ’ AND objid = ’ + convert(varchar(32),@objId)\nEXECUTE (@string) FETCH NEXT FROM lock_cursor INTO @dbid, @ObjId END CLOSE lock_cursor DEALLOCATE lock_cursor\nSELECT * FROM #locktable DROP TABLE #locktable","title":"Who is locking my SQL database?","type":"articles"},{"content":"This is a quick start guide for .NET Gadgeteer and the FEZ Spider Kit. It includes instructions for the installation of necessary software and drivers of the Gadgeteer platform as well as for the first Gadgeteer program. Okay so it does not like Visual Studio 2012, so I next need to download is 1. Microsoft Visual C# Express 2010\nYou can still use professional or ultimate.\n2. Microsoft .NET Micro Framework 4.2 QFE2 SDK\nThis SDK must be installed before step three.\n3. GHI Software Package v4.2 Feb. 18, 2013\nIncludes NETMF and .NET Gadgeteer SDKs and components. See release notes and known issues.\nShould you already have installed C# Express or a full version of Visual Studio 2010. In a second step install the Microsoft .NET Micro Framework 4.2 QFE2 SDK (not 4.1!). You need to create an account on the GHI Electronics website in order to download and install the GHI NETMF v4.2 and .NET Gadgeteer Package in the last step.\nFirst Gadgeteer Application Run Visual C# Express and create a new Project.\nYou will start within the hardware layout view. Drag and drop the following modules from the left toolbox onto the white space near the spider mainboard:\nUsbClientDP module T35_display module Button module Right click on the white space and select “Connect all modules”. The IDE will automatically connect all your selected modules to compatible ports on the spider mainboard. Now all you need to do is to connect your physical modules the same way. Notice that all sockets on the mainboard as well as on the modules have labels on them (X,Y,U;S, etc.) that describe their compatibility (e.g. socket A modules can only be plugged into A sockets on the mainboard).\nPlug the USB mini cable into the UsbClientDB module and connect it with a USB2.0 port on your computer (Hint: USB 3.0 does not work for me!). When the Spider Kit is connected via USB for the first time, Windows will try to install the driver. If it fails, point the driver installation routine to the following folder (you can find the device as EMX in your system device manager):\nC:\\Program Files (x86)\\GHI Electronics\\GHI Premium NETMF v4.2 SDK\\USB Drivers\\GHI_NETMF_Interface\nSelect the Program.cs tab which holds the skeleton code for your first Gadgeteer application. Enter the following lines and hit the “Start Debugger” button in the top of Visual Studio:\nYou can monitor the deployment process in the footer line of Visual Studio. If the process takes too long, try to reset the spider mainboard by pressing the reset button. If deployment is successful a debug window comes up. Press the button module and see what happens on the display. FEZSpider Starter Kit Guide.pdf (8.32 mb)\nTinyclr – Gadgeteer First Project\n","date":"18 February 2013","externalUrl":null,"permalink":"/how-and-setup-and-got-my-gadgeteer-to-work/","section":"Articles","summary":"This is a quick start guide for .NET Gadgeteer and the FEZ Spider Kit. It includes instructions for the installation of necessary software and drivers of the Gadgeteer platform as well as for the first Gadgeteer program. ","title":"How and setup and got my Gadgeteer to work","type":"articles"},{"content":" Hello Kitty in space\nhttps://www.youtube.com/watch?v=5REsCTG4-Gg\u0026amp;feature=player_embedded\n","date":"10 February 2013","externalUrl":null,"permalink":"/going-in-to-space/","section":"Articles","summary":" Hello Kitty in space\nhttps://www.youtube.com/watch?v=5REsCTG4-Gg\u0026feature=player_embedded\n","title":"Going in to Space","type":"articles"},{"content":"I received a tweet yesterday from @gravax who was the Epic Hack of the Day, so just check this out which is pretty cool\ntracert -h 99 216.81.59.173\nYou get back\n12 * * *\n13 episode.iv (206.214.251.1) 155.693 ms 161.675 ms 163.572 ms\n14 a.new.hope (206.214.251.6) 180.764 ms 171.357 ms 162.435 ms\n15 it.is.a.period.of.civil.war (206.214.251.9) 164.476 ms 167.635 ms 155.173 ms\n16 rebel.spaceships (206.214.251.14) 170.381 ms 159.131 ms 163.331 ms\n17 striking.from.a.hidden.base (206.214.251.17) 155.447 ms 168.457 ms 161.968 ms\n18 have.won.their.first.victory (206.214.251.22) 170.991 ms 163.975 ms 156.780 ms\n19 against.the.evil.galactic.empire (206.214.251.25) 157.577 ms 161.265 ms 164.181 ms\n20 during.the.battle (206.214.251.30) 174.856 ms 166.470 ms 192.210 ms\n21 rebel.spies.managed (206.214.251.33) 158.729 ms 172.967 ms 167.352 ms\n22 to.steal.secret.plans (206.214.251.38) 168.628 ms 158.817 ms 186.524 ms\n23 to.the.empires.ultimate.weapon (206.214.251.41) 158.969 ms 155.680 ms 173.059 ms\n24 the.death.star (206.214.251.46) 160.173 ms 179.227 ms 158.865 ms\n25 an.armored.space.station (206.214.251.49) 154.652 ms 165.593 ms 159.269 ms\n26 with.enough.power.to (206.214.251.54) 165.290 ms 170.299 ms 170.502 ms\n27 destroy.an.entire.planet (206.214.251.57) 159.706 ms 163.257 ms 159.500 ms\n28 pursued.by.the.empires (206.214.251.62) 159.571 ms 160.371 ms 163.285 ms\n29 sinister.agents (206.214.251.65) 173.527 ms 170.109 ms 160.567 ms\n30 princess.leia.races.home (206.214.251.70) 158.904 ms 178.839 ms 182.604 ms\n31 aboard.her.starship (206.214.251.73) 168.096 ms 158.851 ms 160.790 ms\n32 custodian.of.the.stolen.plans (206.214.251.78) 162.274 ms 171.099 ms 231.641 ms\n33 that.can.save.her (206.214.251.81) 168.688 ms 167.075 ms 169.212 ms\n34 people.and.restore (206.214.251.86) 160.793 ms 157.587 ms 161.663 ms\n35 freedom.to.the.galaxy (206.214.251.89) 178.962 ms 154.471 ms 160.194 ms\n36 0——————-0 (206.214.251.94) 159.720 ms 157.607 ms 165.869 ms\n37 0——————0 (206.214.251.97) 161.146 ms 174.066 ms 161.739 ms\n38 0—————–0 (206.214.251.102) 166.029 ms 164.294 ms 160.558 ms\n39 0—————-0 (206.214.251.105) 190.757 ms 166.709 ms 186.424 ms\n40 0—————0 (206.214.251.110) 157.325 ms 158.420 ms 181.166 ms\n41 0————–0 (206.214.251.113) 160.496 ms 158.207 ms 160.479 ms\n42 0————-0 (206.214.251.118) 161.534 ms 168.666 ms 157.581 ms\n43 0————0 (206.214.251.121) 157.866 ms 159.754 ms 167.938 ms\n44 0———–0 (206.214.251.126) 163.660 ms 179.243 ms 163.206 ms\n45 0———-0 (206.214.251.129) 168.475 ms 163.112 ms 158.493 ms\n46 0———0 (206.214.251.134) 157.329 ms 158.661 ms 161.612 ms\n47 0——–0 (206.214.251.137) 161.833 ms 164.059 ms 166.384 ms\n48 0——-0 (206.214.251.142) 169.368 ms 182.151 ms 161.276 ms\n49 0——0 (206.214.251.145) 172.806 ms 159.547 ms 169.672 ms\n50 0—–0 (206.214.251.150) 165.376 ms 156.775 ms 169.386 ms\n51 0—-0 (206.214.251.153) 157.625 ms 163.558 ms 162.880 ms\n52 0—0 (206.214.251.158) 179.708 ms 167.693 ms 159.625 ms\n53 0–0 (206.214.251.161) 158.662 ms 163.736 ms 170.034 ms\n54 0-0 (206.214.251.166) 160.455 ms 162.898 ms 172.839 ms\n55 00 (206.214.251.169) 171.892 ms 181.111 ms 157.887 ms\n56 * i (206.214.251.174) 165.980 ms 173.152 ms\n57 by.ryan.werber (206.214.251.177) 166.216 ms 160.726 ms 165.419 ms\n58 when.ccies.get.bored (206.214.251.182) 175.014 ms 180.888 ms 159.231 ms\n59 ccie.38168 (206.214.251.185) 164.865 ms 166.514 ms 183.855 ms\n60 fin (216.81.59.173) 169.747 ms 165.412 ms 165.241 ms\nHow did Ryan Werber do it? Star Wars Traceroute “Bored in the blizzard in Boston; I was inspired by my IRC friend ‘Plazma’ constantly making fun of my reverse dns of scrye.net I came up with this pretty neat hack. It is accomplished using many vrfs on (2) Cisco 1841s. For those less technical, VRFs are essentially private routing tables similar to a VPN. When a packet destined to 216.81.59.173 (AKA obiwan.scrye.net) hits my main gateway, I forward it onto the first VRF on the “ASIDE” router on 206.214.254.1. That router then has a specific route for 216.81.59.173 to 206.214.254.6, which resides on a different VRF on the “BSIDE” router. It then has a similar set up which points it at 206.214.254.9 which lives in another VPN on “ASIDE” router. All packets are returned using a default route pointing at the global routing table. This was by design so the packets TTL expiration did not have to return fully through the VRF Maze. I am a consultant to Epik Networks who let me use the Reverse DNS for an unused /24, and I used PowerDNS to update all of the entries through mysql. This took about 30 minutes to figure out how to do it, and about 90 minutes to implement. All VRFs and DNS were generated by a PHP script. Disclaimer: I am not a very elegant programmer. I can do whatever I need to. I think very linearly and do not plan very well. Below is the code I used to generate the VRFs.” http://beaglenetworks.net ","date":"10 February 2013","externalUrl":null,"permalink":"/hacking-at-its-best-with-dns/","section":"Articles","summary":"I received a tweet yesterday from @gravax who was the Epic Hack of the Day, so just check this out which is pretty cool\ntracert -h 99 216.81.59.173\nYou get back\n12 * * *\n","title":"Hacking at its best with DNS","type":"articles"},{"content":"Following on from my articles on producing smarter code I have come across “50 ways to Avoid, Find and Fix ASP.NET Performance Issues” by RedGate, won’t say it is the best advise but still gives some good tips on how to improve performance.\n50 ways to Avoid, Find and Fix ASP.NET Performance Issues\n50 Ways to Avoid, Find and Fix ASP.NET Performance Issues.pdf (1.22 mb)\n","date":"26 January 2013","externalUrl":null,"permalink":"/avoid-find-and-fix-asp-net-performance-issues/","section":"Articles","summary":"Following on from my articles on producing smarter code I have come across “50 ways to Avoid, Find and Fix ASP.NET Performance Issues” by RedGate, won’t say it is the best advise but still gives some good tips on how to improve performance.\n","title":"Avoid, Find and Fix ASP.NET Performance Issues","type":"articles"},{"content":"Okay second issue I have come across with TypeScript is that even though you can get TypeScript to build your JavaScript files during the build process whist using Visual Studio, when you come to publish the project the JavaScript files are no longer there….!\nWhy?\nWell it is quite simple the Project file does not know about them, so all you need to do is add them to your Project file.\nOne thing worth mentioning here is why don’t you add the JavaScript files directly from Visual Studio? Well you can but when and I am sure you are using a Source Control the JavaScript files will be locked, and if they are locked you won’t be able to get TypeScript to build your files a post compile.\nQuite a simple solution, and one that works.\n","date":"23 January 2013","externalUrl":null,"permalink":"/typescript-not-publishing-its-javascript-files-that-it-builds/","section":"Articles","summary":"Okay second issue I have come across with TypeScript is that even though you can get TypeScript to build your JavaScript files during the build process whist using Visual Studio, when you come to publish the project the JavaScript files are no longer there….!\n","title":"TypeScript not publishing it’s JavaScript files that it builds","type":"articles"},{"content":"TypeScript is great, and it is in Preview from Microsoft. One of the first issues I had was how to get TypeScript to build your JavaScript files every time you build your Visual Studio project.\nSteps to achieve this:\nOpen your project file using editor (so you can see the xml definition) Search for import of Microsoft.Common.targets tag\n\u0026lt;Import Project=”$(MSBuildBinPath)\\Microsoft.Common.targets” /\u0026gt; If you have not found this reference in your project include it, it can be added after \u0026lt;Project *\u0026gt;\nThis will enable for you to have BeforeBuild and AfterBuild events. \u0026lt;Target Name=\"AfterBuild\"\u0026gt; \u0026lt;Message Text=\"After Build\" Importance=\"high\" /\u0026gt; \u0026lt;/Target\u0026gt; \u0026lt;Target Name=\"BeforeBuild\"\u0026gt; \u0026lt;Message Text=\"Before Build\" Importance=\"high\" /\u0026gt; \u0026lt;/Target\u0026gt; Put following xml under first PropertyGroup. This will introduce variables that we are using later on.Note: make sure you have correct version of typescript installed\n\u0026lt;PropertyGroup\u0026gt; \u0026lt;TypeScriptVersion\u0026gt;0.8.1.1\u0026lt;/TypeScriptVersion\u0026gt; \u0026lt;CompileTypeScript\u0026gt;true\u0026lt;/CompileTypeScript\u0026gt; \u0026lt;/PropertyGroup\u0026gt; Now we are ready to introduce our implementation.The following can be inserted in Project tag, its best to add it in the end of the file.\n\u0026lt;Project ToolsVersion=\"4.0\" DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"\u0026gt; \u0026lt;!-- omitted code --\u0026gt; \u0026lt;!-- Insert your implementation --\u0026gt; \u0026lt;/Project\u0026gt; Following tag will get all files from project directory that ends with .ts \u0026lt;ItemGroup\u0026gt; \u0026lt;TypeScriptCompile Include=\"$(ProjectDir)\\**\\*.ts\" /\u0026gt; \u0026lt;/ItemGroup\u0026gt; Update before build event to call our custom target \u0026lt;Target Name=\"BeforeBuild\"\u0026gt; \u0026lt;Message Text=\"Before Build\" Importance=\"high\" /\u0026gt; \u0026lt;CallTarget Targets=\"TypeScriptBuild\"/\u0026gt; \u0026lt;/Target\u0026gt; And our implementation of build for every TypeScript build for every single file.\n\u0026lt;Target Name=\"TypeScriptBuild\" Inputs=\"@(TypeScriptCompile)\" Outputs=\"% (Identity).Dummy\" Condition=\"'$(CompileTypeScript)'=='true'\" \u0026gt; \u0026lt;Message Text=\"Building typescript file - @(TypeScriptCompile)\" Importance=\"high\" /\u0026gt; \u0026lt;Exec Command=\"\"$(MSBuildProgramFiles32)\\Microsoft SDKs\\TypeScript\\$(TypeScriptVersion)\\tsc\" -target ES5 \"@(TypeScriptCompile)\"\" /\u0026gt; \u0026lt;/Target\u0026gt; Thanks for Pavel Svarc for find this out\n","date":"23 January 2013","externalUrl":null,"permalink":"/typescript-and-building-with-your-visual-studio-project/","section":"Articles","summary":"TypeScript is great, and it is in Preview from Microsoft. One of the first issues I had was how to get TypeScript to build your JavaScript files every time you build your Visual Studio project.\n","title":"TypeScript and Building with your Visual Studio Project","type":"articles"},{"content":"Time to get tough and have a bit of fun…..\nThis small project came about when team members kept breaking the builds on our build server, and as a result causing compile errors for other developers when they wanted to work on the latest code.\nSo with a plan in mind I set to task in resolving this issue, first I needed to raise peoples attention that something has gone wrong, so what can I use to do this?\nI could use a flashing light, a siren, both would draw attention, but it these would just signal that something has gone wrong. I need something that will not only signal that something has gone wrong but will also seek out, wait I know the solution a Missile Launcher, both physical and I could get it to fire at the developer who has failed….! Perfect\nI need to find a Missile Launcher that I could programme, and I found one:\nDream Cheeky has the perfect launcher.\nSo after paying $34.99 and it being shipped from Hong Kong, it arrived about a week later\nNext to download the drivers and software from Dream Cheeky, it was not long I had my missiles firing across my room.\nOkay now let’s get hacking.\nI found in the “C:\\Program Files (x86)\\Dream Cheeky\\STORM O.I.C. Missile Launcher” directory a file called USBLib.DLL, so I tried to reference Visual Studio to this file, hay presto it connects, first step completed.\nLet try and connect to the DLL from within Visual Studio\nSo load up the MissileLauncher.cs below and you have an API\nStorm_setup.exe (7.18 mb)\nMissileLauncher.cs (4.67 kb)\nNext step is to interface to Team Foundation Server and detect failed builds, watch this space for the next steps\n","date":"20 January 2013","externalUrl":null,"permalink":"/missile-launcher/","section":"Articles","summary":"Time to get tough and have a bit of fun…..\nThis small project came about when team members kept breaking the builds on our build server, and as a result causing compile errors for other developers when they wanted to work on the latest code.\n","title":"Missile Launcher","type":"articles"},{"content":"Security is always high for installation to customer so is it not about time you encripted the connection string in your web.config file?\nThis is how it looks like before encrypting:\n\u0026lt;connectionStrings\u0026gt; \u0026lt;add name=\"Pubs\" connectionString=\"Server=localhost;Integrated Security=True;Database=Pubs\" providerName=\"System.Data.SqlClient\" /\u0026gt; \u0026lt;add name=\"Northwind\" connectionString=\"Server=localhost;Integrated Security=True;Database=Northwind\" providerName=\"System.Data.SqlClient\" /\u0026gt; \u0026lt;/connectionStrings\u0026gt; We can encrypt any section of your Web.config file on-the-fly and programatically. If you have full access to your Web server, you can encrypt your connection strings with this single command-line located in the in the %windows%\\Microsoft.NET\\Framework\\versionNumber folder:\naspnet_regiis -pe \"connectionStrings\" -app \"/SampleApplication\" Now, the section in your Web.config file will look like this:\n\u0026lt;connectionStrings\u0026gt; \u0026lt;EncryptedData\u0026gt; \u0026lt;CipherData\u0026gt; \u0026lt;CipherValue\u0026gt;AQAAANCMndjHoAw...\u0026lt;/CipherValue\u0026gt; \u0026lt;/CipherData\u0026gt; \u0026lt;/EncryptedData\u0026gt; \u0026lt;/connectionStrings\u0026gt; If you can’t execute commands in your web server, for example, when using shared hosting, you still can encrypt it programatically:\nConfiguration config = Configuration.GetWebConfiguration(Request.ApplicationPath); ConfigurationSection section = config.Sections[\"connectionStrings\"]; section.ProtectSection (\"DataProtectionConfigurationProvider\"); config.Update(); References: Encrypting Web.Config Values in ASP.NET 2.0\n","date":"17 January 2013","externalUrl":null,"permalink":"/encrypting-web-config-for-the-website/","section":"Articles","summary":"Security is always high for installation to customer so is it not about time you encripted the connection string in your web.config file?\nThis is how it looks like before encrypting:\n\u003cconnectionStrings\u003e \u003cadd name=\"Pubs\" connectionString=\"Server=localhost;Integrated Security=True;Database=Pubs\" providerName=\"System.Data.SqlClient\" /\u003e \u003cadd name=\"Northwind\" connectionString=\"Server=localhost;Integrated Security=True;Database=Northwind\" providerName=\"System.Data.SqlClient\" /\u003e \u003c/connectionStrings\u003e We can encrypt any section of your Web.config file on-the-fly and programatically. If you have full access to your Web server, you can encrypt your connection strings with this single command-line located in the in the %windows%\\Microsoft.NET\\Framework\\versionNumber folder:\n","title":"Encrypting Web.config for the website","type":"articles"},{"content":"For a while now I have been reviewing developers code and performing code reviews and I have noticed some common mistakes are being repeated time and time again. These are mostly the mistakes, which once you point them, are quite easy to remember. However, if a developer is not aware of them, they can cause many problems with the efficiency and quality of the developed software. So what are these common mistakes and why are they wrong?\nString concatenation instead of StringBuilder String concatenation works in such a way that every time when you add something to a string, a new address in the memory is being allocated. The previous string is copied to a new location with the newly added part. This is inefficient. On the other hand we have StringBuilder which keeps the same position in the memory without performing the copy operation. Thanks to the strings’ appending by means of StringBuilder the process is much more efficient, especially in case of hundreds of append operations.\n//Just wrong List values = new List(){\"This \",\"is \",\"Sparta \",\"!\"}; string outputValue = string.Empty; foreach (var value in values) { outputValue += value; } //Correct StringBuilder outputValueBuilder = new StringBuilder(); foreach (var value in values) { outputValueBuilder.Append(value); } LINQ – ‘Where’ with ‘First’ instead of FirstOrDefault A lot of programmers find a certain set of elements by means of ‘Where’ and then return the first occurrence. This is inappropriate, because the ‘First’ method can be also applied with the ‘Where’ condition. What’s more, it shouldn’t be taken for granted that the value will always be found. If “First” is used when no value is found, an exception will be thrown. Thus, it’s better to use FirstOrDefault instead. When using FirstOrDefault, if no value has been found, the default value for this type will be returned and no exception will be thrown.\n//Wrong List numbers = new List(){1,4,5,9,11,15,20,21,25,34,55}; return numbers.Where(x =\u0026gt; Fibonacci.IsInFibonacciSequence(x)).First(); /Almost correct return numbers.First(x =\u0026gt; Fibonacci.IsInFibonacciSequence(x)); //Correct return numbers.FirstOrDefault(x =\u0026gt; Fibonacci.IsInFibonacciSequence(x)); Casting by means of ‘(T)’ instead of ‘as (T)’ when possibly not castable It’s common that software developers use simple ‘(T)’ casting, instead of ‘as (T)’. And usually it doesn’t have any negative influence because casted objects are always castable. Yet, if there is even a very slight probability that an object can be under some circumstances not castable, „as (T)” casting should be used. See Difference Between C# Cast Syntax and the AS Operators for more details.\n//Wrong var woman = (Woman)person; //Correct var woman = person as Woman; Not using mapping for rewriting properties There are a lot of ready and very powerful C# mappers (e.g. AutoMapper). If a few lines of code are simply connected with rewriting properties, it’s definitely a place for a mapper. Even if some properties aren’t directly copied but some additional logic is performed, using a mapper is still a good choice (mappers enable defining the rules of rewriting properties to a big extend).\nIncorrect exceptions re-throwing C# programmers usually forget that when they throw an exception using „throw ex” they loose the stack trace, how many times have I seen this? It is then considerably harder to debug an application and to achieve appropriate log messages. When simply using „throw” no data is lost and the whole exception together with the stack trace can be easily retrieved.\n//So So wrong try { //some code that can throw exception [...] } catch (Exception ex) { //some exception logic [...] throw ex; } //Correct try { //some code that can throw exception [...] } catch (Exception ex) { //some exception logic [...] throw; } Not using ‘using’ for objects disposal Many C# software developers don’t even know that ‘using’ keyword is not only used as a directive for adding namespaces, but also for disposing objects. If you know that a certain object should be disposed after performing some operations, always use the ‘using’ statement to make sure that the object will actually be disposed.\n//the below code: using(SomeDisposableClass someDisposableObject = new SomeDisposableClass()) { someDisposableObject.DoTheJob(); } //does the same as: SomeDisposableClass someDisposableObject = new SomeDisposableClass(); try { someDisposableObject.DoTheJob(); } finally { someDisposableObject.Dispose(); } Using ‘foreach’ instead of ‘for’ for anything else than collections Remember that if you want to iterate through anything that is not a collection (so through e.g. an array), using the ‘for’ loop is much more efficient than using the ‘foreach’ loop. See Foreach vs For Performance for more details.\nRetrieving or saving data to DB in more than 1 call This is a very common mistake, especially among junior developers and especially when using ORMs like Entity Framework or NHibernate. Every DB call consumes some amount of time and therefore it’s crucial to decrease the amount of DB calls as much as possible. There are many ways to do so:\nUsing fetching (Eager Loading) Enclosing DB operations in transactions In case of a really complex logic, just moving it to the DB by building a stored procedure With any SQL connections you can always use the SQL Profiler to see what is happening, and it is quite often easy to spot the excessive use of database connections and more so repeated tries of the same routine. Just a few I know, but the more common mistakes that developer make when programming day to day. ","date":"17 January 2013","externalUrl":null,"permalink":"/dont-and-dos-in-c/","section":"Articles","summary":"For a while now I have been reviewing developers code and performing code reviews and I have noticed some common mistakes are being repeated time and time again. These are mostly the mistakes, which once you point them, are quite easy to remember. However, if a developer is not aware of them, they can cause many problems with the efficiency and quality of the developed software. So what are these common mistakes and why are they wrong?\n","title":"Don’t and Do’s in C#","type":"articles"},{"content":"What is a code Review? Code review is systematic examination (often known as peer review) of computer source code. It is intended to find and fix mistakes overlooked in the initial development phase, improving both the overall quality of software and the developers’ skills. Why Reviews are important? Quoting from Code Complete:\n.. software testing alone has limited effectiveness — the average defect detection rate is only 25 percent for unit testing, 35 percent for function testing, and 45 percent for integration testing. In contrast, the average effectiveness of design and code inspections are 55 and 60 percent. Case studies of review results have been impressive:\nIn a software-maintenance organization, 55 percent of one-line maintenance changes were in error before code reviews were introduced. After reviews were introduced, only 2 percent of the changes were in error. When all changes were considered, 95 percent were correct the first time after reviews were introduced. Before reviews were introduced, under 20 percent were correct the first time.\nIn a group of 11 programs developed by the same group of people, the first 5 were developed without reviews. The remaining 6 were developed with reviews. After all the programs were released to production, the first 5 had an average of 4.5 errors per 100 lines of code. The 6 that had been inspected had an average of only 0.82 errors per 100. Reviews cut the errors by over 80 percent.\nThe Aetna Insurance Company found 82 percent of the errors in a program by using inspections and was able to decrease its development resources by 20 percent.\nIBM’s 500,000 line Orbit project used 11 levels of inspections. It was delivered early and had only about 1 percent of the errors that would normally be expected.\nA study of an organization at AT\u0026amp;T with more than 200 people reported a 14 percent increase in productivity and a 90 percent decrease in defects after the organization introduced reviews.\nJet Propulsion Laboratories estimates that it saves about $25,000 per inspection by finding and fixing defects at an early stage.\nThe main goals of code review are:\nTo spot and fix defects early in the process. Better-shared understanding of the code base as team members learn from each other Helps to maintain a level of consistency in design and implementation. Helps to identify common defects across the team thus reducing rework. Builds confidence of stakeholders about technical quality of the execution. Uniformity in understanding will help interchangeability of team members in case of non-availability of any one of them. A different perspective. “Another set of eyes” adds objectivity. Similar to the reason for separating your coding and testing teams, peer reviews provide the distance needed to recognize problems. Pride/reward. Recognition of coding prowess is a significant reward for many programmers. Team cohesiveness. Working together helps draw team members closer. It also provides a brief respite from the isolation that coding often brings. The main areas a reviewer is focusing on are as follows:\nGeneral Unit Testing Comment and Coding Conventions Error Handling Resource Leaks Thread Safety Control Structures Performance Functionality Security Roles and Responsibilities The Developer is the person who has written the code to be reviewed and has initiated the review request. The Reviewer/s: are the people who are going to review the code and report the findings to the developer. Like any skill, good peer reviews come with practice. Some tips that should help you get started on the right track are as follows: Tips for the Developer: The primary reviewer is the author i.e. YOU. Create a checklist for yourself of the things that the code reviews tend to focus on. Some of this checklist should be easy to put together. It should follow the outline of the coding standards document. Because it’s your checklist, you can focus on the thing that you struggle with and skip the things that you rarely, if ever, have a problem with. Run through your code with the checklist and fix whatever you find. Not only will you reduce the number of things that the team finds, you’ll reduce the time to complete the code review meeting—and everyone will be happy to spend less time in the review. You are not your code. Remember that the entire point of a review is to find problems, and problems will be found. Don’t take it personally when one is uncovered. Understand and accept that you will make mistakes. The point is to find them early, before they make it into production. Fortunately, except for the few of us developing rocket guidance software at JPL, mistakes are rarely fatal in our industry, so we can, and should, learn, laugh, and move on. No matter how much “karate” you know, someone else will always know more. Such an individual can teach you some new moves if you ask. Seek and accept input from others, especially when you think it’s not needed. Don’t rewrite code without consultation. There’s a fine line between “fixing code” and “rewriting code.” Know the difference, and pursue stylistic changes within the framework of a code review, not as a lone enforcer. The only constant in the world is change. Be open to it and accept it with a smile. Look at each change to your requirements, platform, or tool as a new challenge, not as some serious inconvenience to be fought. Fight for what you believe, but gracefully accept defeat. Understand that sometimes your ideas will be overruled. Even if you do turn out to be right, don’t take revenge or say, “I told you so” more than a few times at most, and don’t make your dearly departed idea a martyr or rallying cry. Don’t be “the guy in the room.” Don’t be the guy coding in the dark office emerging only to buy cola. The guy in the room is out of touch, out of sight, and out of control and has no place in an open, collaborative environment. Please note that Review meetings are NOT problem solving meetings. Help to maintain the coding standards. Offer to add to the coding standards for things discussed that aren’t in the coding standards. One of the challenges that a developer has in an organization with combative code review practices is that they frequently don’t know where the next problem will come from. If you document each issue into the coding standards, you can check for it with your checklist the next time you come up for code reviews. It also will help cement the concept into your mind so that you’re less likely to miss opportunities to use the feedback. Tips for the Reviewer Critique code instead of people – be kind to the coder, not to the code. As much as possible, make all of your comments positive and oriented to improving the code. Relate comments to local standards, program specs, increased performance, etc. Treat people who know less than you with respect, deference, and patience. Nontechnical people who deal with developers on a regular basis almost universally hold the opinion that we are prima donnas at best and crybabies at worst. Don’t reinforce this stereotype with anger and impatience. The only true authority stems from knowledge, not from position. Knowledge engenders authority, and authority engenders respect – so if you want respect in an egoless environment, cultivate knowledge. Please note that Review meetings are NOT problem solving meetings. Ask questions rather than make statements. A statement is accusatory. “You didn’t follow the standard here” is an attack—whether intentional or not. The question, “What was the reasoning behind the approached you used?” is seeking more information. Obviously, that question can’t be said with a sarcastic or condescending tone; but, done correctly, it can often open the developer up to stating their thinking and then asking if there was a better way. Avoid the “Why” questions. Although extremely difficult at times, avoiding the”Why” questions can substantially improve the mood. Just as a statement is accusatory—so is a why question. Most “Why” questions can be reworded to a question that doesn’t include the word “Why” and the results can be dramatic. For example, “Why didn’t you follow the standards here…” versus “What was the reasoning behind the deviation from the standards here…” Remember to praise. The purposes of code reviews are not focused at telling developers how they can improve, and not necessarily that they did a good job. Human nature is such that we want and need to be acknowledged for our successes, not just shown our faults. Because development is necessarily a creative work that developers pour their soul into, it often can be close to their hearts. This makes the need for praise even more critical. Make sure you have good coding standards to reference. Code reviews find their foundation in the coding standards of the organization. Coding standards are supposed to be the shared agreement that the developers have with one another to produce quality, maintainable code. If you’re discussing an item that isn’t in your coding standards, you have some work to do to get the item in the coding standards. You should regularly ask yourself whether the item being discussed is in your coding standards. Remember that there is often more than one way to approach a solution. Although the developer might have coded something differently from how you would have, it isn’t necessarily wrong. The goal is quality, maintainable code. If it meets those goals and follows the coding standards, that’s all you can ask for. You shouldn’t rush through a code review – but also, you need to do it promptly. Your coworkers are waiting for you. Review fewer than 200-400 lines of code at a time. Security Code Review If the applications requires a very close attention to security then www.owasp.org is the right place for resources. This is a very good Security Code Review document to consider: https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf Assign Severity to Review Finding The severity to find issues with code should go as below. Reviewer must focus on issues with High severity first and then to Medium severity and then Low severity issues. Naming Conventions and Coding style = Low Control Structures and Logical issues = Medium or High Redundant Code = High Performance Issues =High Security Issues = High Scalability Issues= High Functional Issues =High Error Handling = High Reusability = Medium Checklist for developers and reviewers Checklists are a highly recommended way to find the things you forget to do, and are useful for both authors and reviewers. Omissions are the hardest defects to find – after all, it’s hard to review something that’s not there. A checklist is the single best way to combat the problem, as it reminds the reviewer or author to take the time to look for something that might be missing. A checklist will remind authors and reviewers to confirm that all errors are handled, that function arguments are tested for invalid values, and that unit tests have been created. Another useful concept is the personal checklist. Each person typically makes the same 15-20 mistakes. If you notice what your typical errors are, you can develop your own personal checklist. Reviewers will do the work of determining your common mistakes. All you have to do is keep a short checklist of the common flaws in your work, particularly the things you forget to do. As soon as you start recording your defects in a checklist, you will start making fewer of them. The rules will be fresh in your mind and your error rate will drop. We’ve seen this happen over and over. Checklist for Developers My code compiles My code has been developer-tested and includes unit tests My code is tidy (indentation, line length, no commented-out code, no spelling mistakes, etc) I have considered proper use of exceptions I have made appropriate use of logging I have eliminated unused usings’ I have eliminated warnings The code follows the Coding Standards Are there any leftover stubs or test routines in the code? Have I use Separation of Concerns and interface where possible? Are there any hardcoded, development only things still in the code? Was performance considered? Was security considered? Does the code release resources? (HTTP connections, DB connection, files, etc) Corner cases well documented or any workaround for a known limitation of the frameworks Can any code be replaced by calls to external reusable components or library functions? Thread safety and possible deadlocks Checklist for Reviewers Comments are comprehensible and add something to the maintainability of the code Comments are neither too numerous nor verbose Types have been generalized where possible Parameterized types have been used appropriately Exceptions have been used appropriately Repetitive code has been factored out Frameworks have been used appropriately – methods have all been defined appropriately Command classes have been designed to undertake one task only The presentation layer do not contain business logic Unit tests are present and correct Common errors have been checked for Potential threading issues have been eliminated where possible Any security concerns have been addressed Performance was considered The functionality fits the current design/architecture The code is unit testable The code does not use unjustifiable static methods/blocks The code complies to coding standards Logging used appropriately (proper logging level and details) References: http://www.codinghorror.com/blog/2006/05/the-ten-commandments-of-egoless-programming.html http://www.developer.com/java/other/article.php/3579756 http://www.smartbear.com/docs/BestPracticesForPeerCodeReview.pdf http://www.amazon.com/Peer-Reviews-Software-Practical-Guide/dp/0201734850/ref=la_B001IGNXQS_1_3?ie=UTF8\u0026amp;qid=1354616082\u0026amp;sr=1-3 http://www.techrepublic.com/article/developers-guide-to-peer-reviews/1050834 http://smartbear.com/SmartBear/media/pdfs/best-kept-secrets-of-peer-code-review.pdf Original article from: http://insidecoding.com/2013/01/07/code-review-guidelines ","date":"17 January 2013","externalUrl":null,"permalink":"/code-review-guidelines/","section":"Articles","summary":"What is a code Review? Code review is systematic examination (often known as peer review) of computer source code. It is intended to find and fix mistakes overlooked in the initial development phase, improving both the overall quality of software and the developers’ skills. ","title":"Code Review Guidelines","type":"articles"},{"content":"","date":"4 January 2013","externalUrl":null,"permalink":"/categories/iis-7/","section":"Categories","summary":"","title":"IIS 7","type":"categories"},{"content":"Import a Package\nAlways make a backup prior to changing your system. Run the following command to backup an IIS 7.0 or above server:\n%windir%\\system32\\inetsrv\\appcmd add backup “PreMsDeploy” Open the IIS Manager by clicking Start \u0026gt; Run and typing inetmgr. In IIS Manager, expand the Server node and the Sites node, then select the Default Web Site. In the right-hand Actions pane, click the Import Application… link to launch the packaging wizard. Select the package that you created in the previous quick guide, MyApplication.zip, or any other package. In the Install an Application Package dialog, you will see the application and the database. On the Parameters page, enter a new application name if desired and enter a SQL connection string. Click Next to install the package. The Summary page will provide a high-level overview of some items that were installed from the package. The Details tab will give a lot of detail of exactly what was added. For more information go to : http://www.iis.net/learn/publish/using-web-deploy/import-a-package-through-iis-manager\n","date":"4 January 2013","externalUrl":null,"permalink":"/import-a-web-deploy-package-through-iis-manager/","section":"Articles","summary":"Import a Package\nAlways make a backup prior to changing your system. Run the following command to backup an IIS 7.0 or above server:\n%windir%\\system32\\inetsrv\\appcmd add backup “PreMsDeploy” Open the IIS Manager by clicking Start \u003e Run and typing inetmgr. In IIS Manager, expand the Server node and the Sites node, then select the Default Web Site. In the right-hand Actions pane, click the Import Application… link to launch the packaging wizard. Select the package that you created in the previous quick guide, MyApplication.zip, or any other package. In the Install an Application Package dialog, you will see the application and the database. On the Parameters page, enter a new application name if desired and enter a SQL connection string. Click Next to install the package. The Summary page will provide a high-level overview of some items that were installed from the package. The Details tab will give a lot of detail of exactly what was added. For more information go to : http://www.iis.net/learn/publish/using-web-deploy/import-a-package-through-iis-manager\n","title":"Import a Web Deploy Package through IIS Manager","type":"articles"},{"content":"If you come across publishing a SQL databse from a Visual Studio Database Project that the “the script file could not be found”, after a lot of digging around I found that all you need to do is delete the .dbmdl file, and it will publish again.\n","date":"3 January 2013","externalUrl":null,"permalink":"/publish-database-project-causing-the-script-file-could-not-be-found/","section":"Articles","summary":"If you come across publishing a SQL databse from a Visual Studio Database Project that the “the script file could not be found”, after a lot of digging around I found that all you need to do is delete the .dbmdl file, and it will publish again.\n","title":"Publish Database Project causing “the script file could not be found”","type":"articles"},{"content":"In VS 2012 I receive the following error message (one for each table) when trying to build a database project.\nSQL71566: Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlFilegroup cannot not be set on both the Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlTable and the clustered Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlPrimaryKeyConstraint.\nFor reference here is script associated with this error.\nCREATE TABLE [dbo].[OperationsMaster](\n[OperationID] [numeric](18, 0) NOT NULL,\n[OperationName] [nvarchar](150) NOT NULL,\n[OperationTypeID] [numeric](18, 0) NOT NULL,\nCONSTRAINT [PK_OperationsMaster] PRIMARY KEY CLUSTERED\n(\n[OperationID] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY]\nIn above script in last line on word [PRIMARY] red line appears. When I run the same script in SSMS it executed successfully.\nYou can get your project to build by enabling the project setting “Enable extended Transact-SQL verification for common objects.”.\n","date":"3 January 2013","externalUrl":null,"permalink":"/sql71566-when-upgrading-to-vs12/","section":"Articles","summary":"In VS 2012 I receive the following error message (one for each table) when trying to build a database project.\nSQL71566: Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlFilegroup cannot not be set on both the Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlTable and the clustered Microsoft.Data.Tools.Schema.Sql.SchemaModel.SqlPrimaryKeyConstraint.\nFor reference here is script associated with this error.\n","title":"SQL71566 when upgrading to VS12","type":"articles"},{"content":"What is Code UI Testing, or more to the point what is the difference between Unit Tests and Coded UI Tests?\nUnit Tests Tests classes and methods at the API level If it test a UI, it’s testing an abstraction (not quite testing the UI), UI testing has been hard Testing code as you built it We are testing in isolation Coded UI Tests UI testing Testing a running application Simulates a user’s keyboard and mouse activities Test the application that’s pretty much done Integration testing Looking at the layers in your application\nUser Interface Presentation (MVC/MVVM) Domain Model / Service Layer Repository / Data Access The Relational Database (Tables, Views, Stored Procedures etc) The Coded UI tests are only interested in the User Interface, and Unit tests deal with everything else.\nSo\nUnit tests test your API’s\nCoded UI Tests test your running User Interfaces\nSupport for Code UI Operation Systems Windows 7 Windows 8 WIndows Server 2008 R2 Windows Server 8 Web Applications in Internet Explorer 8, 9 and 10 Windows application Windows Form 2.0 and higher WPF 3.5 and higher Dynamics CRM web client Partially Supported Windows Win32 Dynamics (Ax) 2012 MFC Citrix / Terminal Services SharePoint Power Builder For a complete list go to: http://msdn.microsoft.com/en-us/library/dd380742(v=vs.110)\nNo Support for Code UI Browsers Internet Explorer 7 Internet Explorer 8 Chrome Firefox Opera Safari Plugins Silverlight Flash Office Cleint Applications Java SAP Structure of a Coded UI Test The Test Fixture Class [CodedUI] attribute Editable like any other class UIMap.uitest Auto-generated XML-based “map” of your UI Not editable UIMap.designer.cs Supporting information for the test Auto-generated by the recorder Partial class UIMap.cs partial class Customizations and extensions to the UIMap.designer.cs Create Coded UI Tests using the recorder\nCreate Coded UI Tests using MTM Action Recordings\nEditing and extending Coded UI tests\n","date":"28 December 2012","externalUrl":null,"permalink":"/coded-ui-testing/","section":"Articles","summary":"What is Code UI Testing, or more to the point what is the difference between Unit Tests and Coded UI Tests?\nUnit Tests Tests classes and methods at the API level If it test a UI, it’s testing an abstraction (not quite testing the UI), UI testing has been hard Testing code as you built it We are testing in isolation Coded UI Tests UI testing Testing a running application Simulates a user’s keyboard and mouse activities Test the application that’s pretty much done Integration testing Looking at the layers in your application\n","title":"Coded UI Testing","type":"articles"},{"content":"How to get StyleCop working and running in Visual Studio 2012\nFirst download the latest StyleCop from Codeplex, and install.\nIf you now load up Visual Studio and create a new project, how you’ll find lots of underlined code that need attention\nAs you can see form above, we now need to start correcting these, most are due to lack of documentation\nSo once you made the changes things should look better\nNow that we have got it running it is time to start to configure StyleCop, if you right click on your project you’ll find StyleCop Settings\nOne rule which I turn off is SA1126: PrefixCallsCorrectly, just find SA1126 on the Rules tab and uncheck the rule, like this:\nYou’ll need to rerun StyleCop again and you’ll find that this rule is now ignored.\nSetting Up StyleCop MSBuild Integration Next is to get StyleCop running with all builds for your project, to do this check out Setting Up StyleCop for MSBuild Integration\nMSBuild integration will cause the tool to run automatically whenever the code is built, and StyleCop violations will show up alongside compiler errors in the build output.\nIt is possible to set up the build integration so that StyleCop violations will appear as build warnings, or as build errors if so desired.\nInstalling MSBuild Files To enable build integration, first be sure to select the MSBuild option when installing the tool, as shown in the image below:\nThis will cause the StyleCop binaries and supporting MSBuild targets files to be installed under the {Program Files}\\MSBuild\\Microsoft\\StyleCop folder.\nAdding the Import Tag Once the StyleCop MSBuild files are installed, the next step is to import the StyleCop targets file into your C# projects. This is done by adding an Import tag to each C# project file.\nFor example, to integrate StyleCop to the project SampleProject, open the project file SampleProject.csproj within your favorite text editor. Scroll down to the bottom of the file and add a new tag to import the Microsoft.StyleCop.targets file. This import tag should be added just below the import of Microsoft.CSharp.targets:\n\u0026lt;Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"\u0026gt; \u0026hellip;Contents Removed\u0026hellip;\n\u0026lt;Import Project=\u0026quot;$(MSBuildBinPath)\\Microsoft.CSharp.targets\u0026quot; /\u0026gt;\n\u0026lt;Import Project=\u0026quot;$(ProgramFiles)\\MSBuild\\StyleCop\\v4.7\\StyleCop.targets\u0026quot; /\u0026gt;\n\u0026hellip;Contents Removed\u0026hellip;\n\u0026lt;/Project\u0026gt;\nSave the modified .csproj file. The next time you build this project either within Visual Studio or on the command line, StyleCop will run automatically against all of the C# source files within the project.\nBuild Warnings Vs Errors By default, StyleCop violations will show up as build warnings. To turn StyleCop violations into build errors, the flag StyleCopTreatErrorsAsWarnings must be set to false. This flag can be set as an environment variable on the machine, or within the build environment command window. Setting the flag this way will cause StyleCop violations to appear as build errors automatically for all projects where StyleCop build integration is enabled.\nAlternately, this flag can be set within the project file for a particular project. Open the .csproj file for your project again, and find the first PropertyGroup section within the file. Add a new tag to set the StyleCopTreatErrorsAsWarnings flag to false. For example:\n\u0026lt;Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"\u0026gt; \u0026lt;PropertyGroup\u0026gt; \u0026lt;Configuration Condition=\" '$(Configuration)' == '' \"\u0026gt;Debug\u0026lt;/Configuration\u0026gt; \u0026lt;Platform Condition=\" '$(Platform)' == '' \"\u0026gt;AnyCPU\u0026lt;/Platform\u0026gt; \u0026lt;ProductVersion\u0026gt;8.0.50727\u0026lt;/ProductVersion\u0026gt; \u0026lt;SchemaVersion\u0026gt;2.0\u0026lt;/SchemaVersion\u0026gt; \u0026lt;ProjectGuid\u0026gt;{4B4DB6AA-A021-4F95-92B7-B88B5B360228}\u0026lt;/ProjectGuid\u0026gt; \u0026lt;OutputType\u0026gt;WinExe\u0026lt;/OutputType\u0026gt; \u0026lt;AppDesignerFolder\u0026gt;Properties\u0026lt;/AppDesignerFolder\u0026gt; \u0026lt;RootNamespace\u0026gt;SampleProject\u0026lt;/RootNamespace\u0026gt; \u0026lt;AssemblyName\u0026gt;SampleProject\u0026lt;/AssemblyName\u0026gt; \u0026lt;StyleCopTreatErrorsAsWarnings\u0026gt;false\u0026lt;/StyleCopTreatErrorsAsWarnings\u0026gt; \u0026lt;/PropertyGroup\u0026gt; Team Development The configuration described above will suffice to enable StyleCop build integration on an individual development machine. However, development teams working within a well-defined development environment can set up the build integration in a more global way, so that each developer does not have to manually install StyleCop on his machine.\nTo do this, copy all of the files from {Program Files}\\MSBuild\\Microsoft\\StyleCop into a custom folder within your build environment, and check all of these files into your source control system. Next, define an environment variable within your development environment which points to the location of the StyleCop targets file. For example:\nset StyleCopTargets=%enlistmentroot%\\ExternalTools\\StyleCop\\v4.3\\Microsoft.StyleCop.targets\nWith this configuration in place, it is simply a matter of adding the following import tag to each .csproj file within your development environment:\n\u0026lt;Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" /\u0026gt; \u0026lt;Import Project=\"$(StyleCopTargets)\" /\u0026gt; StyleCop will automatically run each time this project is built, no matter who is building the project. There is no need for each developer to install StyleCop manually, since the StyleCop binaries are checked directly into your source control system and are centrally integrated into your build environment.\nCommand Line If this is not enough for you try it from the command link\nmsbuild myproj.csproj /p:StyleCopTreatErrorsAsWarnings=false ","date":"27 December 2012","externalUrl":null,"permalink":"/setting-up-stylecop/","section":"Articles","summary":"How to get StyleCop working and running in Visual Studio 2012\nFirst download the latest StyleCop from Codeplex, and install.\nIf you now load up Visual Studio and create a new project, how you’ll find lots of underlined code that need attention\n","title":"Setting up StyleCop","type":"articles"},{"content":" ASP.NET MVC 4 can be installed side by side with ASP.NET MVC 3 on the same computer, which gives you flexibility in choosing when to upgrade an ASP.NET MVC 3 application to ASP.NET MVC 4.\nThe simplest way to upgrade is to create a new ASP.NET MVC 4 project and copy all the views, controllers, code, and content files from the existing MVC 3 project to the new project and then to update the assembly references in the new project to match any non-MVC template included assembiles you are using. If you have made changes to the Web.config file in the MVC 3 project, you must also merge those changes into the Web.config file in the MVC 4 project.\nTo manually upgrade an existing ASP.NET MVC 3 application to version 4, do the following:\nIn all Web.config files in the project (there is one in the root of the project, one in the Views folder, and one in the Views folder for each area in your project), replace every instance of the following text (note: System.Web.WebPages, Version=1.0.0.0 is not found in projects created with Visual Studio 2012):\nSystem.Web.Mvc, Version=3.0.0.0 System.Web.WebPages, Version=1.0.0.0 System.Web.Helpers, Version=1.0.0.0 System.Web.WebPages.Razor, Version=1.0.0.0 with the following corresponding text:\nSystem.Web.Mvc, Version=4.0.0.0 System.Web.WebPages, Version=2.0.0.0 System.Web.Helpers, Version=2.0.0.0 System.Web.WebPages.Razor, Version=2.0.0.0 In the root Web.config file, update the webPages:Version element to “2.0.0.0” and add a new PreserveLoginUrl key that has the value “true”:\n\u0026lt;appSettings\u0026gt; \u0026lt;add key=\"webpages:Version\" value=\"2.0.0.0\" /\u0026gt; \u0026lt;add key=\"PreserveLoginUrl\" value=\"true\" /\u0026gt; \u0026lt;/appSettings\u0026gt; n Solution Explorer, right-click on the References and select Manage NuGet Packages. In the left pane, select Online\\NuGet official package source, then update the following:\nASP.NET MVC 4 (Optional) jQuery, jQuery Validation and jQuery UI (Optional) Entity Framework (Optonal) Modernizr In Solution Explorer, right-click the project name and then select Unload Project. Then right-click the name again and select Edit ProjectName.csproj.\nLocate the ProjectTypeGuids element and replace {E53F8FEA-EAE0-44A6-8774-FFD645390401} with {E3E379DF-F4C6-4180-9B81-6769533ABE47}.\nSave the changes, close the project (.csproj) file you were editing, right-click the project, and then select Reload Project.\nIf the project references any third-party libraries that are compiled using previous versions of ASP.NET MVC, open the root Web.config file and add the following three bindingRedirect elements under the configuration section:\n\u0026lt;configuration\u0026gt; \u0026lt;!--... elements deleted for clarity ...--\u0026gt; \u0026lt;runtime\u0026gt; \u0026lt;assemblyBinding xmlns=\u0026ldquo;urn:schemas-microsoft-com:asm.v1\u0026rdquo;\u0026gt; \u0026lt;dependentAssembly\u0026gt; \u0026lt;assemblyIdentity name=\u0026ldquo;System.Web.Helpers\u0026rdquo; publicKeyToken=\u0026ldquo;31bf3856ad364e35\u0026rdquo; /\u0026gt; \u0026lt;bindingRedirect oldVersion=\u0026ldquo;1.0.0.0\u0026rdquo; newVersion=\u0026ldquo;2.0.0.0\u0026rdquo;/\u0026gt; \u0026lt;/dependentAssembly\u0026gt; \u0026lt;dependentAssembly\u0026gt; \u0026lt;assemblyIdentity name=\u0026ldquo;System.Web.Mvc\u0026rdquo; publicKeyToken=\u0026ldquo;31bf3856ad364e35\u0026rdquo; /\u0026gt; \u0026lt;bindingRedirect oldVersion=\u0026ldquo;1.0.0.0-3.0.0.0\u0026rdquo; newVersion=\u0026ldquo;4.0.0.0\u0026rdquo;/\u0026gt; \u0026lt;/dependentAssembly\u0026gt; \u0026lt;dependentAssembly\u0026gt; \u0026lt;assemblyIdentity name=\u0026ldquo;System.Web.WebPages\u0026rdquo; publicKeyToken=\u0026ldquo;31bf3856ad364e35\u0026rdquo; /\u0026gt; \u0026lt;bindingRedirect oldVersion=\u0026ldquo;1.0.0.0\u0026rdquo; newVersion=\u0026ldquo;2.0.0.0\u0026rdquo;/\u0026gt; \u0026lt;/dependentAssembly\u0026gt; \u0026lt;/assemblyBinding\u0026gt; \u0026lt;/runtime\u0026gt; \u0026lt;/configuration\u0026gt;\nOriginal article can be found at: MVC 4 release notes\n","date":"9 December 2012","externalUrl":null,"permalink":"/upgrading-an-asp-net-mvc-3-project-to-asp-net-mvc-4/","section":"Articles","summary":" ASP.NET MVC 4 can be installed side by side with ASP.NET MVC 3 on the same computer, which gives you flexibility in choosing when to upgrade an ASP.NET MVC 3 application to ASP.NET MVC 4.\n","title":"Upgrading an ASP.NET MVC 3 Project to ASP.NET MVC 4","type":"articles"},{"content":"If you are like me and you create a number of Custom Build Activities for TFS you want to ensure that you keep them in a tidy place.\nThe best place I have found is to find the BuildProcessTemplates folder and add a new folder called CustomActivities, and in this folder place all your xaml and dll’s files that you have created.\nOnce you’ve created the new folders and files you’ll need to make sure the build controller know about them, click Build \u0026gt; Manage Build Controllers then select the properties and enter :\n$/Microsoft/BuildProcessTemplates/CustomActivies\nunder the Version control path to custom assemblies.\n","date":"8 December 2012","externalUrl":null,"permalink":"/custom-activities-build-process/","section":"Articles","summary":"If you are like me and you create a number of Custom Build Activities for TFS you want to ensure that you keep them in a tidy place.\nThe best place I have found is to find the BuildProcessTemplates folder and add a new folder called CustomActivities, and in this folder place all your xaml and dll’s files that you have created.\n","title":"Custom Activities build process","type":"articles"},{"content":"TFS has the ability to run automatic builds on the build server, this ensures that your project and solutions build and all their dependencies are near by and functional. I’ve looked all over the internet and found various samples, but none that work with Visual Studio 2012 or in the way I wanted the versioning to work. In this post I pulled together everything I have found whist looking over the Internet, I have tried to keep the same process and names as many of the samples I have found while searching for the solution.\nSo what we want to do is to change the standard build process to enable us to do automatic versioning of assemblies. To do this what we need to do is insert some steps in the process just after the source has been retrieved from TFS. We want the workflow that goes something like this:\nGet Latest –\u0026gt; Update AssemblyInfo files with new version –\u0026gt; Build the solution\nWe need to remember that that when team build gets the code from TFS the files are in read only mode, so we’re need to change the read only flag off, change the files, and then turn it back on. What we are not going to do is check the updated assembly info files back into source control. This means all developer builds will by default have a version number of 1.0.0.0 and build server builds will have an incrementing build number. This is a useful way to know if someone has tried to deploy code built on their machine instead of code built by the server.\nThe version number will take the format of Major build (Application major version)\nMinor release (Application minor release)\nDate (month day) (Date of the build)\nIncrementing build number (This number will change on every build)\nWe should end up with a format looking something like this:\n3.1.1207.24353\nBuilding the solution Why do we need a solution, several reasons, we need to be able to build our custom assembly and more importantly we need to be able to edit, change the custom workflow template and then have the ability to compile the workflow to ensure it is built correctly.\n1. Open VS2012 and create a solution with two C# Class LIbrary projects in it. One for the custom build tasks we’re going to create, and one to hold the process template we’re going to change. I have called it CustomBuildActivities and CustomBuildProcess, I’ve opted for both standard Class Libraries, as I wanted to go over what references we need to add in order to build our workflow.\n2, Now go copy the DefaultTemplate.xaml file, which you should find in the Source Control Explorer under the BuildProcessTemplates folder, rename it to something you like and include it in your project. I have called it ExtendedBuildProcess.xaml. Once it’s included in the solution change the Build Action to XamlAppDef. At this point if you try compiling you’ll get a lot of missing references.\nSystem.Activities System.Xaml System.Activities.Presentation PresentationFramework WindowsBase System.Drawing Microsoft.TeamFoundation.Common Microsoft.TeamFoundation.Build.Client Microsoft.TeamFoundation.VersionControl.Client Microsoft.TeamFoundation.VersionControl.Common Microsoft.TeamFoundation.WorkItemTracking.Client %Program Files%\\Microsoft Visual Studio 11.0\\Common7\\IDE\\ReferenceAssemblies\\v2.0\\\nMicrosoft.TeamFoundation.Build.Workflow.dll %Program Files%\\Microsoft Visual Studio 11.0\\Common7\\IDE\\PrivateAssemblies\\\nMicrosoft.TeamFoundation.TestImpact.BuildIntegration.dll %WinDir%\\assembly\\GAC_MSIL\\Microsoft.TeamFoundation.TestImpact.Client\\11.0.0.0__b03f5f7f11d50a3a\\\nMicrosoft.TeamFoundation.TestImpact.Client.dll Quite a lot I know, but I wanted to take you though everything that is needed.\nCreating our Custom Activity The first custom activity we are going to build will be the one we use to toggles the read only flags on AssemblyInfo files. In your CustomBuildActivities project add a new Class called SetReadOnlyFlag. We’ll use this to toggle the read only bits for our AssemblyInfo files later on.\nWe’ll need to add a few references first\nSystem.Activities Microsoft.TeamFoundation.Build.Client Microsoft.TeamFoundation.VersionControl.Client System.IO using System.Activities; using Microsoft.TeamFoundation.Build.Client; using Microsoft.TeamFoundation.VersionControl.Client; using System.IO; namespace CustomBuildActivities { [BuildActivity(HostEnvironmentOption.Agent)] public sealed class SetReadOnlyFlag : CodeActivity { [RequiredArgument] public InArgument\u0026lt;string\u0026gt; FileMask { get; set; }\n[RequiredArgument] public InArgument\u0026lt;bool\u0026gt; ReadOnlyFlagValue { get; set; }\n[RequiredArgument] public InArgument\u0026lt;Workspace\u0026gt; Workspace { get; set; }\nprotected override void Execute(CodeActivityContext context) { var fileMask = context.GetValue(FileMask); var workspace = context.GetValue(Workspace); var readOnlyFlagValue = context.GetValue(ReadOnlyFlagValue);\nforeach (var folder in workspace.Folders) { foreach (var file in Directory.GetFiles(folder.LocalItem, fileMask, SearchOption.AllDirectories)) { var attributes = File.GetAttributes(file); if (readOnlyFlagValue) File.SetAttributes(file, attributes | FileAttributes.ReadOnly); else File.SetAttributes(file,attributes \u0026amp; ~FileAttributes.ReadOnly); } } } } }\nThis is the first Custom Activity done\nUpdate Assembly VersionInfo Custom Activity This Custom Activity is to change all the Version numbers to the format we are after, e.g. 3.1.1207.32454\nusing System; using System.Activities; using System.IO; using System.Text.RegularExpressions; using Microsoft.TeamFoundation.Build.Client; namespace CustomBuildActivities { [BuildActivity(HostEnvironmentOption.Agent)] public sealed class UpdateAssemblyVersionInfo : CodeActivity { [RequiredArgument] public InArgument\u0026lt;string\u0026gt; AssemblyInfoFileMask { get; set; }\n[RequiredArgument] public InArgument\u0026amp;lt;string\u0026amp;gt; SourcesDirectory { get; set; } [RequiredArgument] public InArgument\u0026amp;lt;int\u0026amp;gt; Major { get; set; } [RequiredArgument] public InArgument\u0026amp;lt;int\u0026amp;gt; Minor { get; set; } protected override void Execute(CodeActivityContext context) { var sourcesDirectory = context.GetValue(SourcesDirectory); var major = context.GetValue(Major); var minor = context.GetValue(Minor); var assemblyInfoFileMask = context.GetValue(AssemblyInfoFileMask); var buildDate = int.Parse(string.Format(\u0026quot;{0}{1}\u0026quot;, DateTime.Now.Month, DateTime.Now.Day)); var newVersion = new Version(major, minor, buildDate); foreach (var file in Directory.EnumerateFiles(sourcesDirectory, assemblyInfoFileMask, SearchOption.AllDirectories)) { var text = File.ReadAllText(file); // we want to find 'AssemblyVersion(\u0026quot;1.0.0.0\u0026quot;)' etc foreach (var attribute in new[] { \u0026quot;AssemblyVersion\u0026quot;, \u0026quot;AssemblyFileVersion\u0026quot; }) { var regex = new Regex(attribute + @\u0026quot;\\(\u0026quot;\u0026quot;\\d+\\.\\d+\\.\\d+\\.\\d+\u0026quot;\u0026quot;\\)\u0026quot;); var match = regex.Match(text); if (match.Success) text = regex.Replace(text, attribute + \u0026quot;(\\\u0026quot;\u0026quot; + newVersion + \u0026quot;\\\u0026quot;)\u0026quot;); } } } } }\nOkay that is the coding done, your project should build without and errors, warnings or message, perfect and clean project.\nNow the fun really starts\nUpdating the Extended Build Process Workflow Before we start can you make sure the project builds without an errors.\nWhen you open your ExtendedBuildProcess.xaml on the toolbar you should find the two new CustomBuildActivites (SetReadOnlyFlag and UpdateAssemblyVersionInfo)\nNow comes the tricky bit finding in the workflow where to drop the Custom Activities. You can search the Workflow manually or use the Find option and look for “Get Workspace”, you should end up in the section of the work flow that looks something like this:\nNow add a sequence activity after the get workspace activity:\nNow add your two new Custom Activities to the Sequence activity, with the SetReadOnlyFlag going either side of the UpdateAssemblyVersionInfo.\nSet Activity Properties For each of the new Customer Activities we are going to have to set the required parameters\nSelect the Readonly Activity and then look at the properties\nBefore we set the properties we’ll need to set the Arguments that are coming in to the Workflow, so go to the Arguments tab at the bottom of the workflow.\nClick in the Create Argument box and add a new argument called AssemblyInfoMask and give it a default value of “AssemblyInfo.*”\nCreate a further two arguments AssemblyMajor and AssemblyMinor setting them both to Int32 with 1 and 2 default values.\nYou don’t have to do this process, next but when you do it will appear in the Build process in the correct section. Go to the metadata argument a few lines above and click the ellipsis […] button. You will see a window appear where we can set values that will let Visual Studio know how to display this argument to the end user. Do this for all three arguments. Okay now we have set the argument we can set the properties of the Activity.\nOkay that should be it. So build the solution just to make sure everything is DONE!\nNext just follow the steps to store your new custom activities and then add them in to your build process and you’re done.\nI would not have been able to complete and understand this process without the help of the following two web pages. Customize Team Build 2010 by Ewald Hofman\nHow To: Versioning Builds With TFS 2010 by Richard Banks\n","date":"7 December 2012","externalUrl":null,"permalink":"/enhancing-the-build-in-tfs-2012/","section":"Articles","summary":"TFS has the ability to run automatic builds on the build server, this ensures that your project and solutions build and all their dependencies are near by and functional. I’ve looked all over the internet and found various samples, but none that work with Visual Studio 2012 or in the way I wanted the versioning to work. In this post I pulled together everything I have found whist looking over the Internet, I have tried to keep the same process and names as many of the samples I have found while searching for the solution.\n","title":"Enhancing the Build in TFS 2012","type":"articles"},{"content":"With all this talk about NuGet, NuGet Gallery, I’d thought I’d share with you the NuGet Package Explorer. It is to install and very easy to use too, check out this article on Using the NuGet Package Explorer\n","date":"5 December 2012","externalUrl":null,"permalink":"/nuget-packaging/","section":"Articles","summary":"With all this talk about NuGet, NuGet Gallery, I’d thought I’d share with you the NuGet Package Explorer. It is to install and very easy to use too, check out this article on Using the NuGet Package Explorer\n","title":"NuGet Packaging","type":"articles"},{"content":"Build Process Meets NuGet Gallery The next logical step is integrating your NuGet gallery with your existing build processes. If you don’t have a build process and you’re looking for a little “getting started” guidance with Team Foundation Server (TFS) build processes, check out the Microsoft Visual Studio ALM Rangers Build Customization Guide at rabcg.codeplex.com.\nAll right: You have a library you want to make available on a gallery, which could be the official NuGet Gallery, a proprietary gallery or even a local file share. No matter which, you’ll have to perform certain tasks to create the NuGet package, and they’re generally the same tasks no matter where the gallery resides.\nThrough the course of developing your product, you’ll repetitively go through the process of coding, compiling, packaging, pushing and publishing. You’ll also, we hope, include a couple of healthy doses of testing; results from that testing might make you deviate from publishing to the gallery if you find any issues\nKeeping consumers happy with working software is a good thing, and you’ll have an easier time doing so using a managed process. Remember, though, the managed process can’t be entirely automated; there’s no replacement for human verification. Don’t assume you can publish just because your software passes all the automated tests. You could easily publish a package that isn’t ready and make your consumers angry. Moreover, they won’t be happy if you publish constantly and they can’t keep up with the ever-changing versions. Make publishing a conscious decision.\nUse the build process to build, package and push your NuGet library to a gallery where you perform final tests and do that human verification. That way, you can choose continuous integration or a scheduled build to automatically push the package and make it ready for you to test. How might you do that? Here’s an example using TFS and its workflow-based automated build capability.\nNuGet.exe is a stand-alone, parameter-driven console application, but it can easily be called by another process, such as TFS Team Build. Team Build executes a workflow; in TFS terms, this is a set of custom activities controlled through a build template and initiated by a build definition. One packaged solution for automating the NuGet development process is the NuGetter project at nugetter.codeplex.com. This project provides an automated shell around the NuGet.exe application. We’ll use this package to show what can be done and things to think about as you work toward automating your own NuGet packages.\nThe build definition in TFS is where you provide all the necessary information to do the packaging, push and publish. Building a flexible and repeatable build process for NuGet requires several pieces of data and the switches that turn portions of the process on or off. The data is organized into categories that are titled to give you a sense of the order in which the steps are executed.\nThe PrePackaging section is used for complicated or multiframework NuGet packaging that requires some initial preparation. NuGetter can call a Windows PowerShell script (if you desire) to organize the library files to make packaging easier. This step isn’t required, so you can use the flag parameter “Invoke PowerShell Script” to tell the process whether to execute the script.\nYou can use a .nuspec file directly to define how your package will be created or you can do so indirectly through a .csproj file. It’s up to you; use the approach that better suits your needs.\nAs you can see, all of the parameters required for packaging are included. Version, base path (source folder for packaging), API Key and gallery location (called Source) are all provided as part of the build definition. However, the security of this information might be of great importance to you. For example, the API Key is what allows you and only you to push NuGet packages to the gallery. If that key becomes public, anyone could push bogus packages in your name. Because of this, NuGetter allows you to provide either the actual API Key or a path to a file that contains the key. If you use a file path, the build process reads the file, extracts the key and uses it without listing the key in the log, and security is maintained. Obviously, the build service ID must have read access to the file for this to work.\nAnother potential issue for you is managing the version of your package. In Figure 6, the version number is provided in the build definition. But, do you really want to keep changing that number in the build definition? What happens when you have several builds (continuous integration [CI], daily, other scheduled and various manual builds)? NuGetter gives you the choice to enter the version directly or, as with the API Key, you can provide a file path that multiple build definitions can use. They will all use the same version number and you can manage it in just one place.\nThe Push Destination in the example is the NuGet Gallery, but this is where you provide the build destination even if you’re pushing your package to an internal gallery or to a local file store. This is another case where the build process might need to intervene. NuGet.exe expects a URL as the destination and if you’re pushing to a local store—which won’t be a URL—the process needs to interpret the destination format. In this case, instead of using NuGet.exe to do the pushing, you have the build process do it.\nFor reasons of completeness and feature parity with NuGet.exe, NuGetter does provide for automated publishing. Just keep in mind our earlier caveats before deciding to use this capability.\nOriginal article\n","date":"5 December 2012","externalUrl":null,"permalink":"/building-to-your-nuget-gallery/","section":"Articles","summary":"Build Process Meets NuGet Gallery The next logical step is integrating your NuGet gallery with your existing build processes. If you don’t have a build process and you’re looking for a little “getting started” guidance with Team Foundation Server (TFS) build processes, check out the Microsoft Visual Studio ALM Rangers Build Customization Guide at rabcg.codeplex.com.\n","title":"Building to your NuGet Gallery","type":"articles"},{"content":"Why Host your own NuGet Gallery? NuGet.org already exists as a public repository for NuGet packages, so you might question the point of hosting a gallery. That’s understandable, but what about leveraging that ecosystem infrastructure within the walls of your own dev environment? Why not set up your own private gallery not only to facilitate your product’s development ecosystem but, better yet, to tie it directly to your build and deployment processes? Moreover, anything you see at NuGet.org is available to you free.\nFastest and Simplest The easiest way to host your own NuGet gallery is to expose a file share. This might sound a bit rudimentary, but if you need something fast and simple, this method works extremely well. The share can be structured as you see fit, placing your packages—that is, your *.nupkg files—anywhere on the share. You can refer to the share as a package source.\nWith the package source created, let’s add it to the development environment. You can have as many package sources as desired and easily move between each. To edit your package sources in Visual Studio, navigate to Tools | Options | Package Manager | Package Sources. Note that as of this writing, version 1.5 was current. You should expect slight differences across NuGet versions.\nHere you can add, remove and change the default package source. If you prefer, you can do the same in WebMatrix, a free development environment. Just click on the NuGet Gallery icon on the main menu and select Add Source\nAs you can see, both figures list two package sources. You can choose to use just one or all at any given time.\nIntroducing NuGet Gallery While the file system package source is very easy to set up and start using, it breaks down pretty quickly when you start scaling out. Luckily, NuGet.orgwas built with exactly this in mind, to provide an open platform for people to take, extend and build on for their own needs. You can find the NuGet Gallery project at github.com/NuGet/NuGetGallery. The NuGet Gallery is an ASP.NET MVC 3 project built on top of Razor, OData, SQL Server and Windows Azure.\nThe best way to understand the features and functionality the NuGet Gallery has to offer your development ecosystem is to simply explore NuGet.org.\nBefore you can create and publish a package, you need to be a registered user. Once you’ve registered, you have full rights to upload and manage your packages and edit your profile. You can also generate the unique API key that lets you automate publishing packages to the Gallery (see Figure 3). For more information about publishing a package, please see the previous article in this series, “Becoming a NuGet Author.”\nWhen you upload a package to the NuGet Gallery, it automatically receives its own place in the Gallery\nThis is where you can view all of the important information about a package. For each package, the NuGet Gallery tracks the version downloads, total downloads, dates, licenses and so on. Of course, a package on the NuGet.orgsite will most likely yield considerably larger download numbers given its ecosystem, but these statistics are vital to any package author, regardless of project size.\nThe package feed is clearly the most important feature in the overall stack. It’s an OData feed you’ll find at http://YourGallery/api/v2. This is the same URL you’ll use as your package source. Without this feed, all of the power of NuGet is lost.\nOriginal article\n","date":"5 December 2012","externalUrl":null,"permalink":"/your-very-own-nuget-gallery/","section":"Articles","summary":"Why Host your own NuGet Gallery? NuGet.org already exists as a public repository for NuGet packages, so you might question the point of hosting a gallery. That’s understandable, but what about leveraging that ecosystem infrastructure within the walls of your own dev environment? Why not set up your own private gallery not only to facilitate your product’s development ecosystem but, better yet, to tie it directly to your build and deployment processes? Moreover, anything you see at NuGet.org is available to you free.\n","title":"Your very own NuGet Gallery","type":"articles"},{"content":"With security paramount on all applications here are a few links which will help you get started:\nSeven phases of the traditional software development lifecycle define Security Development Lifecycle (SDL) process.\nMicrosoft Security Development Lifecycle Core Training classes\nPlural Sights also do some good training .NET Security\nASP.NET 3.5 Security\nIntroduction to ASP.NET MVC 3 – Security and ASP.NET MVC 3 ","date":"3 December 2012","externalUrl":null,"permalink":"/net-security/","section":"Articles","summary":"With security paramount on all applications here are a few links which will help you get started:\nSeven phases of the traditional software development lifecycle define Security Development Lifecycle (SDL) process.\nMicrosoft Security Development Lifecycle Core Training classes\n","title":".NET Security","type":"articles"},{"content":"I’m always after the correct download links, and it takes me sometime to make sure I have the right ones, so here they are. As I come up with more I’ll keep this page updated\nMicrosoft .NET Framework 4.5\nhttp://www.microsoft.com/en-us/download/details/?id=30653\nMicrosoft .NET Framework 4 (Standalone Installer)\nhttps://www.microsoft.com/en-gb/download/details/?id=17718\n","date":"2 December 2012","externalUrl":null,"permalink":"/download-links/","section":"Articles","summary":"I’m always after the correct download links, and it takes me sometime to make sure I have the right ones, so here they are. As I come up with more I’ll keep this page updated\n","title":"Download links","type":"articles"},{"content":"MSDeploy is really good for deploying websites and syncing up websites but it can be a real pain to configure and get going intially. The MSDeploy documentation is a bit poor as well and quite often you’ll get a very strange error which can be quite cryptic.\nError Code: ERROR_DESTINATION_NOT_REACHABLE The error message isn’t actually too bad in this case, it’s saying either the Web Management Service isn’t running OR it can’t find MSDeploy. Ok so checklist for this problem:\nWeb Management Service (WMSVC) is running on the target server Port 8172 is open (checked with Telnet for good measure) Can you connect to https://servername:8172/msdeploy.axd Is MSDeploy installed installing the latest version ms MSDeploy did it for me. For a full Microsoft answer check out Configuring a Web Server for Web Deploy Publishing (Web Deploy Handler) http://www.iis.net/learn/publish/using-web-deploy/introduction-to-web-deploy If you are still having troubles go though this set of steps: http://www.iis.net/learn/install/installing-publishing-technologies/installing-and-configuring-web-deploy ","date":"24 November 2012","externalUrl":null,"permalink":"/deploy-website-from-visual-studio-to-iis/","section":"Articles","summary":"MSDeploy is really good for deploying websites and syncing up websites but it can be a real pain to configure and get going intially. The MSDeploy documentation is a bit poor as well and quite often you’ll get a very strange error which can be quite cryptic.\n","title":"Deploy website from Visual Studio to IIS","type":"articles"},{"content":"If you are like me and you don’t like people shouting, you’ll be quite releaved that you can stop the Menus from Visual Studio 2012 from shouting at you by changing the Menus from Uppercase to Lowercase is as simple as adding the following key in the registry:\nHKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\11.0\\General\\SuppressUppercaseConversion REG_DWORD value: 1 ","date":"10 November 2012","externalUrl":null,"permalink":"/vs12-switching-menu-to-lowercase/","section":"Articles","summary":"If you are like me and you don’t like people shouting, you’ll be quite releaved that you can stop the Menus from Visual Studio 2012 from shouting at you by changing the Menus from Uppercase to Lowercase is as simple as adding the following key in the registry:\n","title":"VS12 switching Menu to Lowercase","type":"articles"},{"content":"","date":"22 October 2012","externalUrl":null,"permalink":"/categories/i18n/","section":"Categories","summary":"","title":"I18N","type":"categories"},{"content":"","date":"22 October 2012","externalUrl":null,"permalink":"/categories/internationalization/","section":"Categories","summary":"","title":"Internationalization","type":"categories"},{"content":"Here is our attempt at the XLST translator, main chunk of the work was by Darren, it’s a console application that applies an xsl (i.e. circle.xsl) to some xml (i.e. number.xml) and writes out the result to a console window.\nprivate const String _filename = \"number.xml\"; private const String _stylesheet = \"circle.xsl\"; private const String _culturename = \"en\"; public Program() { //Set the UI to the specified culture. Thread.CurrentThread.CurrentUICulture = new CultureInfo(_culturename); //Create the XslTransform and load the stylesheet. XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(_stylesheet); //Load the XML data file. XPathDocument doc = new XPathDocument(_filename); //Create an XsltArgumentList. XsltArgumentList xslArg = new XsltArgumentList();\n//Add an object to get the resources for the specified language. ResourceTranslator resTran = new ResourceTranslator(\u0026ldquo;Resources.Resource\u0026rdquo;); xslArg.AddExtensionObject(\u0026ldquo;urn:myResTran\u0026rdquo;, resTran);\n//Add an object to calculate the circumference of the circle. Calculate obj = new Calculate(); xslArg.AddExtensionObject(\u0026ldquo;urn:myObj\u0026rdquo;, obj);\n//Create an XmlTextWriter to output to the console. XmlTextWriter writer = new XmlTextWriter(Console.Out);\n//Transform the file. xslt.Transform(doc, xslArg, writer, null);\nwriter.Close();\n} //Calculates the circumference of a circle given the radius. public class Calculate { public static double Circumference(double radius) { return Math.PI * 2 * radius; } } The translation is based upon our database resource translator i.e. a class that creates a resource manager based on the default/neutral resource resx, and implements a Find method. This method takes a string that we want to find (specified in the default language i.e. in our case English) which is then effectively used as a key into the resource file(s). The text that is passed into the Find method is first converted into a valid identifier (e.g. spaces removed, slashes removed etc… etc…), before it can be used as a key. Then, if a key exists for the specified culture (French in the case of the test solution) then the appropriate language version of the original passed in text is returned. In order to use the resource translator in the xsl, an object of this type is first created and then passed into the xsl using extension objects. The Find method can then be called by referencing the correct extension object, and specifying the piece of text that we would like to be translated. public string Find(string displayText) { if (displayText == null) return null; var assem = System.Reflection.Assembly.Load(\u0026quot;Resources\u0026quot;); var rman = new ResourceManager(_baseName, assem); var s = rman.GetString(Regex.Replace(displayText, \u0026quot;[^\\\\w]\u0026quot;, string.Empty, RegexOptions.CultureInvariant)); return s jQuery15201710984220262617_1352536393022 displayText; }\nXslResourceTranslator.zip (90.45 kb)\nSource can be found on GitHub https://github.com/BryanAvery/XslResourceTranslator\n","date":"22 October 2012","externalUrl":null,"permalink":"/need-to-localize-an-xslt/","section":"Articles","summary":"Here is our attempt at the XLST translator, main chunk of the work was by Darren, it’s a console application that applies an xsl (i.e. circle.xsl) to some xml (i.e. number.xml) and writes out the result to a console window.\n","title":"Need to Localize an XSLT","type":"articles"},{"content":"If you are like me, some customer just can’t upgrade from SQL 2000, so how do you use the EntityFramework 4.0+ with SQL Server 2000?\nHere is one solution that has worked for me:\nHere are the steps to add a new Entity Framework 4.0+ entity context to a Visual Studio 2010 project:\nDownload the base entity data model for SQL Server 2000 file and save it to the project folder to which you wish to add the SQL 2000 entity context. Do NOT add it to your project yet. Rename the EDMX file to the name of the data context. Open the EDMX file in a text editor. Find/replace all references to %DB_NAME% with your own value. Add this new connection string section to your App or Web.config and find/replace with your own values: \u0026lt;connectionStrings\u0026gt; \u0026lt;add name=\"%DB_NAME%Entities\" connectionString=\"metadata=res://*/%DB_NAME%.csdl|res://*/%DB_NAME%.ssdl|res://*/%DB_NAME%.msl;provider=System.Data.SqlClient;provider connection string=\"Data Source=%DB_HOST_NAME%;Initial Catalog=%DB_NAME%;Persist Security Info=True;User ID=%DB_USER%;Password=%DB_USER_PWD%;MultipleActiveResultSets=False\"\" providerName=\"System.Data.EntityClient\" /\u0026gt; \u0026lt;/connectionStrings\u0026gt; Please note: the connection string name MUST MATCH the EntityContainer section name you specified in the EDMX file.\nFind/replace all references to %DB_NAME% in the App or Web.config file with your own value as above. After the .edmx and web.config files configured, add them to the project and verify the new entity data source appears after refreshing the Data Source manager window. If you can’t double click on your *.edmx file you’ll need to right click on it and select “Open with”, and choose “ADO.NET Entity Data Model Designer” If the new entity data source appears, open the .edmx file in design view and refresh the design model. Now you have your Entity XML file next you can generate your Code by using the T4 templete code generation. To do this just right click in the EDMX model and select “Add Code Generation Item” this will give you the installed Generators (you can get more from NUGET, like dbcontext”\nI’ve found this very useful and gives you a head start on old databases.\n","date":"7 October 2012","externalUrl":null,"permalink":"/entityframework-4-0-and-sql-2000/","section":"Articles","summary":"If you are like me, some customer just can’t upgrade from SQL 2000, so how do you use the EntityFramework 4.0+ with SQL Server 2000?\nHere is one solution that has worked for me:\nHere are the steps to add a new Entity Framework 4.0+ entity context to a Visual Studio 2010 project:\n","title":"EntityFramework 4.0 and SQL 2000","type":"articles"},{"content":"So you’ve upgraded to iOS 6 and keen to tryout all the new features one of them being the Passbook, time to get rid of all those printed tickets and even start thinking of replacing that old leather wallet.\nSo you click on the Passbook\nThen you tap the App Store button to see what apps that are supported with Passbook.\nIf you are like me you’ll get “Can’t connect to iTunes Store” error But wayhay I found the old solution of setting the date forward manually cure this issue. It takes a few easy steps to manually change the date.\nOpen Settings Open General Open Date \u0026amp; Time Turn off Automatically setting to Off Open Set Date \u0026amp; Time set the date to one year ahead Now try out the Passbook and you’ll be able to connect to the Apps Store, if you are like me you’ll be disappointed as only two apps are currently available United Airlines and Lufthansa, none of which I use or have any intention of using. Oh don’t forget to reset your Date to Automatic ","date":"21 September 2012","externalUrl":null,"permalink":"/ios-6-passbook-problem/","section":"Articles","summary":"So you’ve upgraded to iOS 6 and keen to tryout all the new features one of them being the Passbook, time to get rid of all those printed tickets and even start thinking of replacing that old leather wallet.\n","title":"iOS 6 Passbook problem","type":"articles"},{"content":"Looking at large scale Databases.docx (298.57 kb)\n","date":"15 August 2012","externalUrl":null,"permalink":"/large-scale-database/","section":"Articles","summary":"Looking at large scale Databases.docx (298.57 kb)\n","title":"Large Scale Database","type":"articles"},{"content":"I’ve been playing with SQL Server Broker services to allow me to notify my C# code when some data has been changed, but first you need to enable SSB (SQL Server Broker). The easiest way of doing this is to us the following SQL statement:\nalter database [\u0026lt;dbname\u0026gt;] set enable_broker with rollback immediate; The reason for using rollback immediate is that the statement needs to have exclusive access to the database, and any connection has a shared lock on it, even when idle.\n","date":"29 June 2012","externalUrl":null,"permalink":"/sql-server-broker/","section":"Articles","summary":"I’ve been playing with SQL Server Broker services to allow me to notify my C# code when some data has been changed, but first you need to enable SSB (SQL Server Broker). The easiest way of doing this is to us the following SQL statement:\n","title":"SQL Server Broker","type":"articles"},{"content":"I’ve been a strong advocator of MEF for some time now, and with some of my work is now based around MS Workflow I thought it would be a good time to get MEF working with MS Workflow.\nBefore we start we need to know a few things:\nMS Workflow does not have a normals constructor When will we import our objects Two simple tasks for any normal project, but MS Workflow is different, as we all know.\nSo to start with to deal with te fact that MS Workflow does not have any constructors we can use Extensions, as these are fired up when MS Workflow is started up. To do this it is simpley a task to add the extension in to the web.config file under \u0026lt;extensions\u0026gt; tag\n\u0026lt;extensions\u0026gt; \u0026lt;behaviorExtensions\u0026gt; \u0026lt;add name=\"mefProviderExtension\" type=\"MEFExtension.WorkflowServiceBehaviorElement, MEFExtension\"/\u0026gt; \u0026lt;/behaviorExtensions\u0026gt; \u0026lt;/extensions\u0026gt; The code by default picks up the Exported MEF objects from the BIN folder and a bin/PlugIns folder, however you can have a test in bin/tests folder, to do this you can add to behavioura mefProviderExtension\n\u0026lt;mefProviderExtension useTestServices=\"true\"/\u0026gt; Then with every CodeActivity use the MEF method of SatisfyImportOnce to inject the MEF objects.\ncontext.GetExtension\u0026lt;MefWorkflowProvider\u0026gt;().Container.SatisfyImportsOnce(this); I have taken the code written by Gareth Berlow from CodePlex called MEF and Workflow Services Integration and adapted the code to make it easier to use, simply but moving all the MEF code in to a MEFExtension but still allowing the ability to generate your own overrides of the MEF object if required.\nMSWorkflow _MEF.zip (66.04 kb)\n","date":"30 April 2012","externalUrl":null,"permalink":"/mef-with-ms-workflow/","section":"Articles","summary":"I’ve been a strong advocator of MEF for some time now, and with some of my work is now based around MS Workflow I thought it would be a good time to get MEF working with MS Workflow.\n","title":"MEF with MS Workflow","type":"articles"},{"content":"I wanted to have a play with jQuery AutoComplete, so like many people I found the source and created a HTML page locally on my machine. Then you test it out, save it, uploaded it, or email it to where you need it.\nWell no more jsFiddle is a playground for such trivial tasks, you can build HTML, CSS and JavaScript all online. It even allows you to choose a Framework (such a jQuery) and different versions.\nSo this was my first attempt at using the jQuery AutoComplete\nhttp://jsfiddle.net/VwcV3/1/\n","date":"25 March 2012","externalUrl":null,"permalink":"/jsfiddle-lovely-online-tool-for-trying-out-your-javascript/","section":"Articles","summary":"I wanted to have a play with jQuery AutoComplete, so like many people I found the source and created a HTML page locally on my machine. Then you test it out, save it, uploaded it, or email it to where you need it.\n","title":"JSFiddle, lovely online tool for trying out your javaScript","type":"articles"},{"content":"","date":"12 March 2012","externalUrl":null,"permalink":"/categories/mef/","section":"Categories","summary":"","title":"MEF","type":"categories"},{"content":"After travelling for a year I was interest to see if MEF would work with MVC, and after some digging around I found it can.\n***UPDATED****\nAdded a CastleWindsor example\nWith any MEF you’ll need a Composition Factory which in this case I’ll place in the MEF directory, but it can be in a different project if required.\npublic class CompositionContainerFactory { public CompositionContainer CreateContainer() { var path = HostingEnvironment.MapPath(\"~/bin\"); if (path == null) throw new Exception(\u0026quot;Unable to find the path\u0026quot;); var catalog = new DirectoryCatalog(path); return new CompositionContainer(catalog); } }\u0026lt;/pre\u0026gt; Now comes the interesting part, in MVC 3 Microsoft introduced the IDependencyResolver, which gets the services when needed.\nSo implementing the IDependencyResolver with MEF was a little trickier\npublic class MEFDependencyResolver : IDependencyResolver { private readonly CompositionContainer _container; public MEFDependencyResolver(CompositionContainer container) { if (container == null) throw new ArgumentNullException(\u0026quot;container\u0026quot;); _container = container; } public object GetService(Type serviceType) { if (serviceType == null) throw new ArgumentNullException(\u0026quot;serviceType\u0026quot;); var name = AttributedModelServices.GetContractName(serviceType); return Enumerable.Any(_container.Catalog.Parts.SelectMany(part =\u0026amp;gt; part.ExportDefinitions), e =\u0026amp;gt; e.ContractName == name) ? _container.GetExportedValue\u0026amp;lt;object\u0026amp;gt;(name) : null; } public IEnumerable\u0026amp;lt;object\u0026amp;gt; GetServices(Type serviceType) { if (serviceType == null) throw new ArgumentNullException(\u0026quot;serviceType\u0026quot;); var name = AttributedModelServices.GetContractName(serviceType); return _container.GetExportedValues\u0026amp;lt;object\u0026amp;gt;(name); } }\u0026lt;/pre\u0026gt; The final step we will need to set the Dependency Resolver and this is done in the Application Start inside the Global.asax\nprotected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); DependencyResolver.SetResolver(new MEFDependencyResolver(new CompositionContainerFactory().CreateContainer())); }\u0026lt;/pre\u0026gt; Now we are ready to use MEF inside of MVC.\nTo use MEF inside of MVC just attach the [Export] attribute to controller and then import the object you require, like this:\n[Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class HomeController : Controller { [ImportMany] private List\u0026lt;IAddress\u0026gt; Addresses { get; set; } public ActionResult Index() { return View(Addresses); } }\u0026lt;/pre\u0026gt; Make sure that the Part Creation Policy is Non-Shared otherwise you will only be able to visit the page once.\nThat is it, what more could you want, oh the code samples, which I have update to MVC 5.2\nDI_Controller_Sample\nCastleWindsorControllerInjection\n","date":"12 March 2012","externalUrl":null,"permalink":"/using-mef-in-mvc-3/","section":"Articles","summary":"After travelling for a year I was interest to see if MEF would work with MVC, and after some digging around I found it can.\n***UPDATED****\nAdded a CastleWindsor example\nWith any MEF you’ll need a Composition Factory which in this case I’ll place in the MEF directory, but it can be in a different project if required.\n","title":"Using MEF in MVC to inject Controllers","type":"articles"},{"content":"If when in a test invironment you need to test out SSL (HTTPS) on your website you can create a self-assigning SSL certificate (this process only appiles to IIS6)\nTypically, Secure Socket Layer (SSL) Certificates are created for domains by first generating a Certificate Signing Request (CSR) through Internet Information Services (IIS), sending the request to a known Certification Authority, such as GeoTrust, which generates a corresponding Certificate file for use in conjunction with the CSR, completing the request and securing communications on the domain.\nHowever, IIS does come with the ability to create a ‘self-signed’ certificate, in which the server generating the CSR also generates the corresponding Certificate file. These are mainly used for testing, development and troubleshooting, as the certificate will only be recognized as valid by the server it is hosted on. Attempting to view the secured domain externally would receive an error that the certificate is not valid, as it has not been approved nor is recognized by a known Certification Authority.\nTo create a self-signed SSL certificate for any hosted domain on your server, you will first need to download and install the SSL Diagnostics Kit v1.1, which can be obtained free of charge from Microsoft via the following URL: SSL Diagnostics Version 1.1 (x86) – SSLDiag.msi (532.00 kb)\nGiven the option to either Run or Save the file, choose ‘Save’.\nFor now, let’s save the file to the desktop. Click ‘Save’ again.\nOnce the download is complete, double-click the icon to begin the installation.\nClick ‘Next’ on the initial window.\nEnter your desired Name and Company information, and click ‘Next’.\nThe next screen will provide options for which type of installation you prefer. You can click ‘Complete’ to install the Diagnostics.\nYou are now ready to install the diagnostics. Click ‘Install’.\nWhen the installer confirms it has completed, click ‘Finish’.\nNow, we need to get some information from IIS before we can generate the self-signed certificate. Open IIS by navigating to ‘Start –\u0026gt; Administrative Tools –\u0026gt; Internet Information Services (IIS) Manager’.\nOnce IIS is open, expand the Server Name, then click on the ‘Web Sites’ folder. This will bring up a list of all web sites on the server in the right-hand pane. You will notice that each site has a unique number assigned to it under the ‘Identifier’ column. This is the number which we need in order to create the self-signed certificate. As you can see, the Identifier for ‘example.com’ is 957.\nNext, we need to open a DOS Prompt. You can do this by navigating to ‘Start –\u0026gt; Run’, typing ‘CMD’, and clicking OK.\nOnce the DOS prompt is open, we will need to navigate to the directory where the SSL Diagnostic Toolkit is located. This directory is ‘C:\\Program Files\\IIS Resources\\SSLDiag’. To navigate to this directory, at the DOS prompt, enter the following command:\ncd C:\\Program Files\\IIS Resources\\SSLDiag\nThe ‘cd’ command stands for Change Directory. Press Enter once the command is typed in, and the prompt will bring you right to the directory, as seen below.\nNow, we need to enter the command which will actually create the certificate. The base command to create the certificate is ‘ssldiag /selfssl’, however command requires certain parameters for the certificate to be successfully created. These parameters are as follows:\n/N: – This specifies the common name of the certificate. The computer name is used if there is no common name specified.\n/K: – This specifies the key length of the certificate. The default is length 1024.\n/V: – This specifies the amount of time the certificate will be valid for, calculated in days. The default setting is seven days.\n/S: – This specifies the Identifier of the site, which we obtained earlier. The default will always be 1, which is the Default Web Site in IIS.\nLet’s use the following command to create a self-signed certificate for ‘example.com’ (you’ll need to ensure that the DNS server has this domain name pointing to your IIS machine) which is valid for two years, using a common name of ‘www.example.com’, a key length of 1024:\nssldiag /selfssl /N:CN=example.com /K:1024 /V:730 /S:957\nOnce you have set the parameters to your preference, enter the command into the DOS prompt, and press Enter. After pressing Enter, the DOS prompt will simply move to the next line.\nNow, we can check IIS and verify the certificate is now in place. Using the steps outlined above, navigate back to IIS, right-click on the domain, and choose ‘Properties’.\nInside the Properties window, click on the ‘Directory Security’ tab.\nOn the Directory Security tab, under the ‘Secure Communications’ heading, click on the ‘View Certificate’ button, as it is now enabled.\nThis windows confirms the certificate has been successfully installed. Note the ‘Issued By’ field, as typically the issuer would be a known Certification Authority, such as GeoTrust, however here the issuer is ‘example.com’. This confirms the certificate is self-signed. Click OK to close the window.\nYou can now view the site on the server under a secure heading. Again, please note that as the certificate is self-signed, and does not have a matching Root Certificate from a Certification Authority, attempting to view the site under a secure heading from an external location will cause a certificate error. Self-signed certificates should only be used for testing and development, and under no circumstances should be substituted for a CA-approved SSL Certificate for a live, production website.\nThis has been extracted from ServiceFirst Support\n","date":"9 March 2012","externalUrl":null,"permalink":"/assigning-ssl-certificate-in-iis-6/","section":"Articles","summary":"If when in a test invironment you need to test out SSL (HTTPS) on your website you can create a self-assigning SSL certificate (this process only appiles to IIS6)\nTypically, Secure Socket Layer (SSL) Certificates are created for domains by first generating a Certificate Signing Request (CSR) through Internet Information Services (IIS), sending the request to a known Certification Authority, such as GeoTrust, which generates a corresponding Certificate file for use in conjunction with the CSR, completing the request and securing communications on the domain.\n","title":"Assigning SSL certificate in IIS 6","type":"articles"},{"content":"If you are like me you perform a shuffle before checking anything in to a Source Control Repository and TFS is no different\nAs for shuffle:\nGet Latest Fix merge conflicts Build Fix build errors Run tests Fix broken tests Go to 1 (until there is nothing new to get) Only check in when all steps are complete.\nThen check the Pending Changes that you have nothing else left to check in, if you do then perform the above shuffle for each pending change.\nTo get to the Pending Changes window select View–\u0026gt;Other Windows–\u0026gt;Pending Changes\nOther useful references:\nhttp://codebetter.com/jeremymiller/2005/07/25/using-continuous-integration-better-do-the-check-in-dance/\nhttp://www.extremeprogramming.org/rules/collective.html\n","date":"5 March 2012","externalUrl":null,"permalink":"/the-tfs-shuffle/","section":"Articles","summary":"If you are like me you perform a shuffle before checking anything in to a Source Control Repository and TFS is no different\nAs for shuffle:\nGet Latest Fix merge conflicts Build Fix build errors Run tests Fix broken tests Go to 1 (until there is nothing new to get) Only check in when all steps are complete.\n","title":"The TFS shuffle","type":"articles"},{"content":"This is the second part of my Raspberry PI posts, the first covered the installation of Debian on to a virtual machine. This this post I’ll be getting the fresh install to include a lightweight desktop called LXDE So first up your Debian and login\nHere is the set of command you need to type to get LXDE up and running:\nsu root apt-get install lode xorg apt-get install server-xorg-video-all exit starts One last thing I’ll show you is installing packages, as we’ll be using the Raspberry PI we’ll be using the Aptitude which is an old-fashioned GUI interface to assist in installing packages\naptitude So that’s it for today, you have a good looking interface and the ability to install packages\n","date":"4 March 2012","externalUrl":null,"permalink":"/debian-and-installing-lxde-lightweight-x11-desktop-environment/","section":"Articles","summary":"This is the second part of my Raspberry PI posts, the first covered the installation of Debian on to a virtual machine. This this post I’ll be getting the fresh install to include a lightweight desktop called LXDE ","title":"Debian and installing LXDE (Lightweight X11 Desktop Environment)","type":"articles"},{"content":"","date":"4 March 2012","externalUrl":null,"permalink":"/categories/raspberry-pi/","section":"Categories","summary":"","title":"Raspberry PI","type":"categories"},{"content":"I’ve ordered my Raspberry PI, so I’m planning how and what I’m going to be doing with it.\nI have many small projects I’d like to get underway, but ones which spring to mind first are building a home Media Centre, Network Storage device that supports many drives, and one that is hot on my list is the ability to connect the Raspberry PI to my Arduino and build a small portable device that can tell me where and how to access Wifi while I’m out and about.\nBut before I do anything lets get a virtual machine up and running so we can start playing as if we were on the Raspberry PI:\nIt has been rumoured that Debian will be the preferred OS to use on the PI due to it small foot print, so let go and get it\nhttp://www.debian.org/distrib/netinst\nI selected and downloaded small CDs and the kfreebsb-i386, mainly because I am running on a Mac and will be running my virtual machine inside of Parallels.\nThing to remember when creating your virtual machine is set your memory to 256mg as this is all you’ll have to play with inside your PI.\nHere is a YouTube video that I made which goes through the installation of Debian in real time, as it takes under 15 minutes to install\nSo first steps complete.\nThe next Blog on the Raspberry PI will be to install a graphical user interface on to your Debian operating system.\n","date":"4 March 2012","externalUrl":null,"permalink":"/getting-ready-for-my-raspberry-pi-and-installing-debian/","section":"Articles","summary":"I’ve ordered my Raspberry PI, so I’m planning how and what I’m going to be doing with it.\nI have many small projects I’d like to get underway, but ones which spring to mind first are building a home Media Centre, Network Storage device that supports many drives, and one that is hot on my list is the ability to connect the Raspberry PI to my Arduino and build a small portable device that can tell me where and how to access Wifi while I’m out and about.\n","title":"Getting ready for my Raspberry PI and installing Debian","type":"articles"},{"content":"Always up for cheating, so when I came across a website dedicated to cheat sheets I was over the moon. http://www.addedbytes.com/\nThe one I am using the most has to be RegEx as I am now finally getting to grips with the syntax and expressions. regular-expressions-cheat-sheet-v1.pdf (568.89 kb)\n","date":"28 February 2012","externalUrl":null,"permalink":"/regular-expression-cheat-sheet/","section":"Articles","summary":"Always up for cheating, so when I came across a website dedicated to cheat sheets I was over the moon. http://www.addedbytes.com/\nThe one I am using the most has to be RegEx as I am now finally getting to grips with the syntax and expressions. ","title":"Regular Expression cheat sheet","type":"articles"},{"content":"After finding Screen Toaster some three years ago now, I found out the other month that the website has been pulled, it’s a shame as this was such a useful tool.\nBut today I found Screen-O-Matic a small java application, like Screen Toaster, that just works.\nYou don’t even need an account, and if you want to go Pro it’s only $12 a year. Lets hope that this model is sustainable and long lasting.\n","date":"22 February 2012","externalUrl":null,"permalink":"/screencast-o-matic/","section":"Articles","summary":"After finding Screen Toaster some three years ago now, I found out the other month that the website has been pulled, it’s a shame as this was such a useful tool.\nBut today I found Screen-O-Matic a small java application, like Screen Toaster, that just works.\n","title":"Screencast-O-matic","type":"articles"},{"content":"I’ve been pushing Balsamiq Mockups for a number of years, it was on my toy list for 2009.\nOnce you have a mock up of your wireframe and the customer is happy with the look, the next stage is to convert it to HTML, previously I have prefered to pass this to a designer to make it look pretty. But the problem you’ll have with making something look nice is that the customer will think it is DONE and you just don’t want that to happen.\nI came across a Balsamiq Mockup to HTML/CSS converter this morning from NedeCo it just does the job and generates a simple and easy to follow HTML and CSS.\nThis is a perfect starting point for your application and you’ll be able to get your business and architecture up and working before the customer gets any expectitions of a DONE project.\nBalsamiqConverter.zip (511.03 kb)\n","date":"21 February 2012","externalUrl":null,"permalink":"/balsamiq-mockups-the-next-stage/","section":"Articles","summary":"I’ve been pushing Balsamiq Mockups for a number of years, it was on my toy list for 2009.\nOnce you have a mock up of your wireframe and the customer is happy with the look, the next stage is to convert it to HTML, previously I have prefered to pass this to a designer to make it look pretty. But the problem you’ll have with making something look nice is that the customer will think it is DONE and you just don’t want that to happen.\n","title":"Balsamiq Mockups the next stage","type":"articles"},{"content":"Have you tried to upgrade an MVC 2.0 application to MVC 3.0, it’s not easy as you need to change a lot of configuration.\nWell Eilon Lipton has a codeplex project to make life easier ASP.NET MVC 3 Application Upgrader. This is a standalone application that takes the troubles away for you and delivers an MVC 3.0 application\nMvc3AppConverter.zip (430.58 kb)\n","date":"17 February 2012","externalUrl":null,"permalink":"/upgrading-from-mvc-2-0-to-mvc-3-0/","section":"Articles","summary":"Have you tried to upgrade an MVC 2.0 application to MVC 3.0, it’s not easy as you need to change a lot of configuration.\nWell Eilon Lipton has a codeplex project to make life easier ASP.NET MVC 3 Application Upgrader. This is a standalone application that takes the troubles away for you and delivers an MVC 3.0 application\n","title":"Upgrading from MVC 2.0 to MVC 3.0","type":"articles"},{"content":"Hands-On Labs Razor\nc# code\n@Html.ActionLink(“Edit”, Edit”, new {id=item.ID})\nimplicit code\n@items\nCode block\n@{\nHtml.ActionLink(“Edit”, Edit”, new {id=item.ID})\n}\nDisplaying text inside a code block\n\u0026lt;Text\u0026gt;Review\u0026lt;/Text\u0026gt;\nExplicit expression using brackets\n@(item.Rating)\nThis is an email address\nK@item.Rating\nif you use an explicit expression you’ll display the values\nK@(item.Rating)\nIf you want @OdeToCode you can ESC by using @@OdeToCode\n","date":"15 February 2012","externalUrl":null,"permalink":"/mvc-crib-sheet/","section":"Articles","summary":"Hands-On Labs Razor\nc# code\n","title":"mvc crib sheet","type":"articles"},{"content":"I came across some nice C# samples from Microsoft today providing everything from Hello World, to how to use Yield and how to program Attributes.\nOfficial Visual Studio 2010 Samples for C# 4.0\nWorth having a look at if you are a beginner or a seasoned programmer.\nLanguage Samples The C# 4.0-specific samples are called:\nNamed and Optional Office Sample Python Sample Simple Variance. Here is the complete list of language samples:\nAnonymous Delegates: Demonstrates the use of unnamed delegates to reduce application complexity. Arrays: Shows how to use arrays. Attributes: Shows how to create custom attribute classes, use them in code, and query them through reflection. Collection Classes: Shows how to make non-generic collection classes that can be used with the foreach statement. COM Interop Part I: Shows how to use C# to interoperate with COM objects. COM Interop Part II: Shows how to a use a C# server together with a C++ COM client. Commandline: Demonstrates simple command-line processing and array indexing. Condiational Methods: Demonstrates conditional methods, which provide a powerful mechanism by which calls to methods can be included or omitted depending on whether a symbol is defined. Delegates: Shows how delegates are declared, mapped to static and instance methods, and combined into multicast delegates. Events: Shows how to declare, invoke, and configure events in C#. Explicit Interface: Demonstrates how to explicitly implement interface members and how to access those members from interface instances. Generics: Shows how to make generic collection classes that can be used with the foreach statement. Hello World: A Hello World application. Indexers Part I: Shows how C# classes can declare indexers to provide array-like access to objects. Indexers Part II: Shows how to implement a class that uses indexed properties. Indexed properties enable you to use a class that represents an array-like collection. Libraries: Shows how to use compiler options to create a DLL from multiple source files; also, how to use the library in other programs Named and Optional (C# 4.0): Demonstrates Named and Optional parameters, an alternative to method overloads Nullable: Demonstrates value types, such as double and bool, that can be set to null Office Sample (C# 4.0): Demonstrates how Dynamic and COM Interop make it easy to call Microsoft Office in C# 4.0 OLEDB: Demonstrates how to use a Microsoft Access database from C# by creating a dataset and adding tables to it. Operator Overloading: Shows how user-defined classes can overload operators Partial Types: Demonstrates how classes and structures can be defined in multiple C# source-code files PInvokeShows how to call exported DLL functions from C# Properties: Shows how properties are declared and used; also demonstrates abstract properties Python Sample (C# 4.0): Learn how to call a Python script by using the Dynamic feature in C# 4.0 Security: Discusses .NET Framework security and shows two ways to modify security permissions in C#: using permission classes and permission attributes Simple Variance (C# 4.0): See how Covariance and Contravariance are supported in generic interfaces and delegates Structs: Shows how to use structs in C#. Threading: Demonstrates various thread activities such as creating and executing a thread, synchronizing threads, interacting between threads, and using a thread pool Unsafe: Shows how to use unmanaged code (code that uses pointers) in C# User Conversions: Shows how to define conversions to and from user-defined types Versioning: Demonstrates versioning in C# by using the override and new keywords XML Documents: Shows how to document code by using XML Yield: Demonstrates how to use the yield keyword to filter items in a collection LinqSamples These samples help you learn LINQ quickly. They also act as a reference and guide for those with existing LINQ experience. A few handy utilities are also included. They are available in the LinqSamples folder.\nDynamicQuery: Code to create LINQ queries at run time. LinqToNorthwind: A basic example of how to use LINQ To SQL to query a database LinqToXmlDataBinding: Bind LINQ to XML code to WPF controls ObjectDumper: A utility for writing the output from a LINQ query to the screen in text mode PasteXmlAsLinq: A Visual Studio addin that automatically converts XML to LINQ to XML. QueryVisualizer: Allows LINQ to SQL developers to see the SQL for their query, and also to see the results of the query in a grid. Reflector: Use LINQ to right queries against the objects in your code using the Reflection APIs RSS: This sample acts as a tiny web server that aggregates several RSS feeds SampleQueries: This is the most important sample and contains about 500 examples of how to use each of the query operators in LINQ to Objects, LINQ to SQL, LINQ to XML and LINQ to DataSet. SimpleLambdas: Several examples of how to write and use lambda expressions SimpleLinqToObjects: The hello world of the LINQ samples. This shows you how easy it is to do simple queries of in-memory objects using LINQ to Objects. SimpleLinqToXml: Get started using LINQ to XML. WebServiceLinqProvider(TerraService): A custom LINQ provider and client for the TerraServer-USA Web service. Whitepapers: The following papers are stored in this directory in Word format: LINQ Project Overview LINQ to SQL Overview for C# and VB Standard Query Operators LINQ to XML Overview WinFormsDataBinding: Learn how to display LINQ queries with grids in a Windows form. It includes a one to many query example. XQuery: Another simple LINQ to XML sample query. This sample shows the minimal code necessary to write a LINQ to XML query ","date":"14 February 2012","externalUrl":null,"permalink":"/visual-c-and-net-4-0-samples/","section":"Articles","summary":"I came across some nice C# samples from Microsoft today providing everything from Hello World, to how to use Yield and how to program Attributes.\nOfficial Visual Studio 2010 Samples for C# 4.0\nWorth having a look at if you are a beginner or a seasoned programmer.\n","title":"Visual C# and .NET 4.0 samples","type":"articles"},{"content":"http://channel9.msdn.com/Shows/Workflow-TV/endpointtv-Lab-Introduction-to-WF4-Exercise-3-The-Code-Activity\n","date":"13 February 2012","externalUrl":null,"permalink":"/resources-for-workflow/","section":"Articles","summary":"http://channel9.msdn.com/Shows/Workflow-TV/endpointtv-Lab-Introduction-to-WF4-Exercise-3-The-Code-Activity\n","title":"Resources for Workflow","type":"articles"},{"content":"One great feature about the Mac is the way the mouse movement is active on a window without the need to click on the window. This is called XWindows mode.\nWell I have just found out you can do this in Windows too:\nTo turn this setting on, just type “mouse works” into the search box in the Control Panel, and you should see an item called “Change how your mouse works”.\nIn this screen, scroll down and find the checkbox for “Activate a window by hovering over it with the mouse”.\nNow life becomes easier.\n","date":"8 February 2012","externalUrl":null,"permalink":"/windows-mouse-acting-like-a-mac-mouse/","section":"Articles","summary":"One great feature about the Mac is the way the mouse movement is active on a window without the need to click on the window. This is called XWindows mode.\nWell I have just found out you can do this in Windows too:\n","title":"Windows mouse acting like a Mac mouse","type":"articles"},{"content":"I came across this nice little MVC routing checker by Phil Haacket\nhttp://haacked.com/archive/2008/03/13/url-routing-debugger/\nSimple to use just add\nRouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes); in to the Application_Start of your Global.asax and it does all the reporting on all your Routings\nRouteDebug-Binary.zip (4.80 kb)\nRouteTesterDemo.zip (16.81 kb)\n","date":"2 February 2012","externalUrl":null,"permalink":"/asp-net-mvc-routing-checker/","section":"Articles","summary":"I came across this nice little MVC routing checker by Phil Haacket\nhttp://haacked.com/archive/2008/03/13/url-routing-debugger/\nSimple to use just add\nRouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes); in to the Application_Start of your Global.asax and it does all the reporting on all your Routings\n","title":"ASP.NET MVC Routing checker","type":"articles"},{"content":"With MVC getting more popular each day and C# increasing the market share (Tiobe index) and your applications getting larger it is worth looking in to how to Internationalise your application, the source of all sources for internationalization is Guy Smith-Ferrier and his blog is a source of wealthy knowledge.\nIt’s well worth taking a look at How To Achieve World(-Ready) Domination In ASP.NET MVC 4 by Guy Smith-Ferrier\nI came across this useful post for MVC and Internationalization by Nadeem Afana’s, the original post can be found here\nIntroduction If your website targets users from different parts of the world, these users might like to see your website content in their own language. Creating a multilingual website is not an easy task, but it will certainly allow your site to reach more audience. Fortunately, the .NET Framework already has components that support different languages and cultures.\nWe will build an ASP.NET MVC 3 web application that contains the following features:\nIt can display contents in different languages. It autodetects the language from the user’s browser. It allows the user to override the language of their browser. Globalization and Localization in ASP.NET\nInternationalization involves Globalization and Localization. Globalization is the process of designing applications that support different cultures. Localization is the process of customizing an application for a given culture.\nThe format for the culture name is “\u0026lt;languagecode2\u0026gt;-\u0026lt;country/regioncode2\u0026gt;”, where \u0026lt;languagecode2\u0026gt; is the language code and \u0026lt;country/regioncode2\u0026gt; is the subculture code. Examples include es-CL for Spanish (Chile) and en-US for English (United States).\nASP.NET keeps track of two culture values, the Culture and UICulture. The culture value determines the results of culture-dependent functions, such as the date, number, and currency formatting. The UICulture determines which resources are to be loaded for the page by the ResourceManager. The ResourceManager simply looks up culture-specific resources that is determined by CurrentUICulture. Every thread in .NET has CurrentCulture and CurrentUICulture objects. So ASP.NET inspects these values when rendering culture-dependent functions. For example, if current thread’s culture (CurrentCulture) is set to “en-US” (English, United States), DateTime.Now.ToLongDateString() shows “Saturday, January 08, 2011”, but if CurrentCulture is set to “es-CL” (Spanish, Chile) the result will be “sábado, 08 de enero de 2011”.\nHow to Support Different Languages in ASP.NET MVC 3\nThere are two ways to incorporate different languages and cultures in ASP.NET MVC 3:\nBy using resource strings in all our site views. (See part 2) By using different set of views for every language and locale. By mixing between 1 and 2 Which one is the best?\nIt depends on you. It is a matter of convenience. Some people prefer to use a single view for all languages because it is more maintainable. While others think replacing views content with code like “@Resources.Something” might clutter the views and will become unreadable. Recall that views have to be as simple as possible. If your views look fine with a lot of inline code, it’s fine. But sometimes you have no choice in languages where layout has to be different like right-to-left languages. Perhaps, a mix of the two is the best. Anyway, in this example we will use the 2nd approach just to show a different way than the usual resource strings.\nViews Naming Conventions\nIn order to create different views for every culture, we will append the culture name to the name of the view. For example, Index.cshtml (the default view), Index.es-CL.cshtml (Spanish, Chile), Index.ar-JO.cshtml (Arabic, Jordan). The view name that has no ending is considered the default culture. A default culture view will be rendered if the requested culture name is not implemented explicitly.\nGlobalizing our Web Site We will create a new ASP.NET MVC 3 web application and globalize it step by step.\nClick “File-\u0026gt;New Project” menu command within Visual Studio to create a new ASP.NET MVC 3 Project. We’ll create a new project using the “Internet Application” template.\nCreating the Model\nWe’ll need a model to create our web application. Add a class named “User” to the “Models” folder:\nInternationalizing Validation Messages\nOur model presented above contains no validation logic, and this is not the case in normal applications nowadays. We can use data annotation attributes to add some validation logic to our model. However, in order to globalize validation messages, we need to specify a few extra parameters. The “ErrorMessageResourceType” indicates the type of resource to look up the error message. “ErrorMessageResourceName” indicates the resource name to lookup the error message. Resource manager will pick the correct resource file based on the current culture.\nNow modify the “Person” class and add the following attributes:\nnamespace MvcInternationalization.Models { public class Person { [Required(ErrorMessageResourceType=typeof(MyResources.Resources), ErrorMessageResourceName=\"FirstNameRequired\")] [StringLength(50, ErrorMessageResourceType = typeof(MyResources.Resources), ErrorMessageResourceName = \"FirstNameLong\")] public string FirstName { get; set; } [Required(ErrorMessageResourceType = \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;typeof\u0026lt;/span\u0026gt;(MyResources.Resources), ErrorMessageResourceName = \u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;LastNameRequired\u0026quot;\u0026lt;/span\u0026gt;)] [StringLength(50, ErrorMessageResourceType = \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;typeof\u0026lt;/span\u0026gt;(MyResources.Resources), ErrorMessageResourceName = \u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;LastNameLong\u0026quot;\u0026lt;/span\u0026gt;)] \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;public\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;string\u0026lt;/span\u0026gt; LastName { get; set; } [Required(ErrorMessageResourceType = \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;typeof\u0026lt;/span\u0026gt;(MyResources.Resources), ErrorMessageResourceName = \u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;AgeRequired\u0026quot;\u0026lt;/span\u0026gt;)] [Range(0, 130, ErrorMessageResourceType = \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;typeof\u0026lt;/span\u0026gt;(MyResources.Resources), ErrorMessageResourceName = \u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;AgeRange\u0026quot;\u0026lt;/span\u0026gt;)] \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;public\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;int\u0026lt;/span\u0026gt; Age { get; set; } [Required(ErrorMessageResourceType = \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;typeof\u0026lt;/span\u0026gt;(MyResources.Resources), ErrorMessageResourceName = \u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;EmailRequired\u0026quot;\u0026lt;/span\u0026gt;)] [RegularExpression(\u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;.+@.+\\\\..+\u0026quot;\u0026lt;/span\u0026gt;, ErrorMessageResourceType = \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;typeof\u0026lt;/span\u0026gt;(MyResources.Resources), ErrorMessageResourceName = \u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;EmailInvalid\u0026quot;\u0026lt;/span\u0026gt;)] \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;public\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;string\u0026lt;/span\u0026gt; Email { get; set; } \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;public\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;string\u0026lt;/span\u0026gt; Biography { get; set; } } }\nLocalizing Data Annotations Validation Messages\nBecause we need to perform data validation on our model using Data Annotations, we will have to add translated resource strings for every culture our site will support. In this case, English, Spanish, and Arabic.\nWe will store resource files in a separate assembly, so we can reference them in other project types in the future.\nRight click on the Solution and then choose the “Add-\u0026gt;New Project” context menu command. Choose “Class Library” project type and name it “MyResources”.\nNow right click on “MyResources” project and then choose “Add-\u0026gt;New Item” context menu command. Choose “Resource File” and name it “Resources.resx”. This will be our default culture (en-US) since it has no special endings. Add the following names and values to the file like below:\nRemember to mark the resource’s access modifier property to “public”, so it will be accessible from other projects.\nNow create a new resource file and name it “Resources.es-CL.resx” and add the following names and values like below:\nNow, do the same for the Arabic version. You may not be able to enter the correct strings by keyboard because your OS may not be configured to accept Arabic. However, you can download the files from the link at the top. Anyway, the resource file is included for reference:\nWe need to reference “MyResources” project from our web application, so that we can read the resource strings right from our web site. Right click on “References” under our web project “MvcInternationalization”, and choose the “MyResources” project from Projects tab.\nDetermining Culture\nHow do we determine which version of a view to return to the end user? How do we know which culture does the user want?\nThere is a header field called “Accept-Language” that the browser sends on every request. This field contains a list of culture names (language-country) that the user has configured in their browser. The problem is that this culture may not reflect the real user’s preferred language, such as a computer in a cybercafé. We should allow the user to choose a language explicitly and allow them even to change it. In order to do this sort of things, we need to store the user’s preferred language in a store, which can be perfectly a cookie.\nWe will create a base controller that inspects the cookie contents first, if there is no cookie, we will use the “Accept-Language” field sent by their browser. Create a controller and name it “BaseController” like below:\nnamespace MvcInternationalization.Controllers { public class BaseController : Controller { \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;protected\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;override\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;void\u0026lt;/span\u0026gt; OnActionExecuted(ActionExecutedContext filterContext) { \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// Is it View ?\u0026lt;/span\u0026gt; ViewResultBase view = filterContext.Result \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;as\u0026lt;/span\u0026gt; ViewResultBase; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;if\u0026lt;/span\u0026gt; (view == \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;null\u0026lt;/span\u0026gt;) \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// if not exit\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;return\u0026lt;/span\u0026gt;; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;string\u0026lt;/span\u0026gt; cultureName = Thread.CurrentThread.CurrentCulture.Name; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// e.g. \u0026quot;en-US\u0026quot; // filterContext.HttpContext.Request.UserLanguages[0]; // needs validation return \u0026quot;en-us\u0026quot; as default \u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// Is it default culture? exit\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;if\u0026lt;/span\u0026gt; (cultureName == CultureHelper.GetDefaultCulture()) \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;return\u0026lt;/span\u0026gt;; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// Are views implemented separately for this culture? if not exit\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;bool\u0026lt;/span\u0026gt; viewImplemented = CultureHelper.IsViewSeparate(cultureName); \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;if\u0026lt;/span\u0026gt; (viewImplemented == \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;false\u0026lt;/span\u0026gt;) \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;return\u0026lt;/span\u0026gt;; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;string\u0026lt;/span\u0026gt; viewName = view.ViewName; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;int\u0026lt;/span\u0026gt; i = 0; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;if\u0026lt;/span\u0026gt; (\u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;string\u0026lt;/span\u0026gt;.IsNullOrEmpty(viewName)) viewName = filterContext.RouteData.Values[\u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;action\u0026quot;\u0026lt;/span\u0026gt;] + \u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;.\u0026quot;\u0026lt;/span\u0026gt; + cultureName; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// Index.en-US\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;else\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;if\u0026lt;/span\u0026gt; ((i = viewName.IndexOf(\u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;'.'\u0026lt;/span\u0026gt;)) \u0026amp;gt; 0) { \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// contains . like \u0026quot;Index.cshtml\u0026quot; \u0026lt;/span\u0026gt; viewName = viewName.Substring(0, i + 1) + cultureName + viewName.Substring(i); } \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;else\u0026lt;/span\u0026gt; viewName += \u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;.\u0026quot;\u0026lt;/span\u0026gt; + cultureName; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// e.g. \u0026quot;Index\u0026quot; ==\u0026amp;gt; \u0026quot;Index.en-Us\u0026quot;\u0026lt;/span\u0026gt; view.ViewName = viewName; filterContext.Controller.ViewBag._culture = \u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;.\u0026quot;\u0026lt;/span\u0026gt; + cultureName; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;base\u0026lt;/span\u0026gt;.OnActionExecuted(filterContext); } \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;protected\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;override\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;void\u0026lt;/span\u0026gt; ExecuteCore() { \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;string\u0026lt;/span\u0026gt; cultureName = \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;null\u0026lt;/span\u0026gt;; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// Attempt to read the culture cookie from Request\u0026lt;/span\u0026gt; HttpCookie cultureCookie = Request.Cookies[\u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;_culture\u0026quot;\u0026lt;/span\u0026gt;]; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;if\u0026lt;/span\u0026gt; (cultureCookie != \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;null\u0026lt;/span\u0026gt;) cultureName = cultureCookie.Value; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;else\u0026lt;/span\u0026gt; cultureName = Request.UserLanguages[0]; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// obtain it from HTTP header AcceptLanguages\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// Validate culture name\u0026lt;/span\u0026gt; cultureName = CultureHelper.GetValidCulture(cultureName); \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// This is safe\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// Modify current thread's culture \u0026lt;/span\u0026gt; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName); Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultureName); \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;base\u0026lt;/span\u0026gt;.ExecuteCore(); } } }\nThe base controller checks if the cookie exists, and sets the current thread culture to that cookie value. Of course, because cookie content can be manipulated on the client side, we should always validate its value using a helper class called “CultureHelper”. If the culture name is not valid, the helper class returns the default culture. After that, when we call “Return” in controller action methods, the view name is modified by the base controller behind the scenes to reflect the correct culture in cookie or header field. This way we make sure that the user gets the right content based on their culture.\nCultureHelper Class\nThe CultureHelper is basically a utility that allows us to store culture names we are implementing in our site:\nnamespace MvcInternationalization.Utility { public static class CultureHelper { // Include ONLY cultures you are implementing as views private static readonly Dictionary\u0026lt;String, bool\u0026gt; _cultures = new Dictionary\u0026lt;string,bool\u0026gt; { {\"en-US\", true}, // first culture is the DEFAULT {\"es-CL\", true}, {\"ar-JO\", true} }; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;/// \u0026amp;lt;summary\u0026amp;gt;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;/// Returns a valid culture name based on \u0026quot;name\u0026quot; parameter. If \u0026quot;name\u0026quot; is not valid, it returns the default culture \u0026quot;en-US\u0026quot;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;/// \u0026amp;lt;/summary\u0026amp;gt;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;/// \u0026amp;lt;param name=\u0026quot;name\u0026quot;\u0026amp;gt;Culture's name (e.g. en-US)\u0026amp;lt;/param\u0026amp;gt;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;public\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;static\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;string\u0026lt;/span\u0026gt; GetValidCulture(\u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;string\u0026lt;/span\u0026gt; name) { \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;if\u0026lt;/span\u0026gt; (\u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;string\u0026lt;/span\u0026gt;.IsNullOrEmpty(name)) \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;return\u0026lt;/span\u0026gt; GetDefaultCulture(); \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// return Default culture\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;if\u0026lt;/span\u0026gt; (_cultures.ContainsKey(name)) \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;return\u0026lt;/span\u0026gt; name; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// Find a close match. For example, if you have \u0026quot;en-US\u0026quot; defined and the user requests \u0026quot;en-GB\u0026quot;, \u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// the function will return closes match that is \u0026quot;en-US\u0026quot; because at least the language is the same (ie English) \u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;foreach\u0026lt;/span\u0026gt;(var c \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;in\u0026lt;/span\u0026gt; _cultures.Keys) \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;if\u0026lt;/span\u0026gt; (c.StartsWith(name.Substring(0, 2))) \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;return\u0026lt;/span\u0026gt; c; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// else \u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;return\u0026lt;/span\u0026gt; GetDefaultCulture(); \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// return Default culture as no match found\u0026lt;/span\u0026gt; } \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;/// \u0026amp;lt;summary\u0026amp;gt;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;/// Returns default culture name which is the first name decalared (e.g. en-US)\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;/// \u0026amp;lt;/summary\u0026amp;gt;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;/// \u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;public\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;static\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;string\u0026lt;/span\u0026gt; GetDefaultCulture() { \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;return\u0026lt;/span\u0026gt; _cultures.Keys.ElementAt(0); \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// return Default culture\u0026lt;/span\u0026gt; } \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;/// \u0026amp;lt;summary\u0026amp;gt;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;/// Returns \u0026quot;true\u0026quot; if view is implemented separatley, and \u0026quot;false\u0026quot; if not.\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;/// For example, if \u0026quot;es-CL\u0026quot; is true, then separate views must exist e.g. Index.es-cl.cshtml, About.es-cl.cshtml\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;/// \u0026amp;lt;/summary\u0026amp;gt;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;/// \u0026amp;lt;param name=\u0026quot;name\u0026quot;\u0026amp;gt;Culture's name\u0026amp;lt;/param\u0026amp;gt;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;/// \u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt;\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;public\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;static\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;bool\u0026lt;/span\u0026gt; IsViewSeparate(\u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;string\u0026lt;/span\u0026gt; name) { \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;return\u0026lt;/span\u0026gt; _cultures[name]; } } }\nWe should populate “_cultures” manually. The “_cultures” dictionary stores the list of culture names our site supports. The first parameter indicates culture name (e.g. en-US), the second parameter indicates whether we are implementing separate views for that culture. If the second parameter is false, the default view is used (ie the one that has no special ending).\nThe nice part of this utility class is that it serves similar languages. For example, if a user is visiting our site from Argentina (es-ar), a culture which is not implemented in our site, he or she will see our site in Spanish using “es-cl” (Spanish, Chile) instead of English language. This way, you don’t have to implement all cultures unless you really care about currency, date format, etc.\nControllers\nVisual Studio has created a controller named “HomeCotnroller” for us, so we’ll use it for simplicity. Modify the “HomeController.cs” so that it looks like below:\nnamespace MvcInternationalization.Controllers { public class HomeController : BaseController { [HttpGet] public ActionResult Index() { \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;return\u0026lt;/span\u0026gt; View(); } [HttpPost] \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;public\u0026lt;/span\u0026gt; ActionResult Index(Person per) { \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;return\u0026lt;/span\u0026gt; View(); } \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;public\u0026lt;/span\u0026gt; ActionResult SetCulture(\u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;string\u0026lt;/span\u0026gt; culture) { \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// Validate input\u0026lt;/span\u0026gt; culture = CultureHelper.GetValidCulture(culture); \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// Save culture in a cookie\u0026lt;/span\u0026gt; HttpCookie cookie = Request.Cookies[\u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;_culture\u0026quot;\u0026lt;/span\u0026gt;]; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;if\u0026lt;/span\u0026gt; (cookie != \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;null\u0026lt;/span\u0026gt;) cookie.Value = culture; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// update cookie value\u0026lt;/span\u0026gt; \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;else\u0026lt;/span\u0026gt; { cookie = \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;new\u0026lt;/span\u0026gt; HttpCookie(\u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;_culture\u0026quot;\u0026lt;/span\u0026gt;); cookie.HttpOnly = \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;false\u0026lt;/span\u0026gt;; \u0026lt;span class=\u0026quot;rem\u0026quot;\u0026gt;// Not accessible by JS.\u0026lt;/span\u0026gt; cookie.Value = culture; cookie.Expires = DateTime.Now.AddYears(1); } Response.Cookies.Add(cookie); \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;return\u0026lt;/span\u0026gt; RedirectToAction(\u0026lt;span class=\u0026quot;str\u0026quot;\u0026gt;\u0026quot;Index\u0026quot;\u0026lt;/span\u0026gt;); } \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;public\u0026lt;/span\u0026gt; ActionResult About() { \u0026lt;span class=\u0026quot;kwrd\u0026quot;\u0026gt;return\u0026lt;/span\u0026gt; View(); } } } The “SetCulture” action allows the user to change their current culture and stores it in a cookie called “_culture”. We are not restricted to cookies, we could instead save the culture name in Session or elsewhere, but cookies are really lightweight since they do not take any type of space on server side.\nCreating a View Template\nNow we will implement the View associated with the HomeController’s Index action. First delete the existing Index.cshtml file under “Views/Home” folder. Now to implement the view right-click within the “HomeController.Index()” method and select the “Add View” command to create a view template for our home page:\nWe will need to modify some of the settings above. Choose the option “Create a strongly-typed view” and choose the “Person” class we created before. Also, choose the “Create” menu item from the “Scaffold template” drop-down box.\nWhen we click the “Add” button, a view template of our “Create” view (which renders the form) is created. Modify it so it looks like below:\nThe javascript code simply post back the form to set the culture. The “selected” helper is used to mark the appropriate culture radio button as checked.\nNow make two copies of “Index.cshtml” and rename them to “Index.es-CL.cshtml” and “Index.ar-JO.cshtml”. These latter views represent the localized versions of Index.cshtml for two different cultures, so we can add whatever is necessary inside them. Make them look like below:\nSpanish view\nArabic view\nOf course, for simple partial views like “_LogOnPartial.cshtml” and which are not referenced by controllers, we can use resource strings perfectly.\nArabic view\nTry It Out\nRun the website now. Notice that client side validation is working nicely. Click on radio buttons to switch between cultures, and notice how right-to-left language is showing correctly. Using separate views allowed us to control how to position elements, and have made our views clean and readable.\nEnglish\nSpanish\nArabic\nClient-Side localization What about client-side scripts?\nFor client-side, we should worry mainly about numbers, date and time, and messages since these change from culture to culture. There are many ways to implement client-side localization. But here are two common options:\nCreating standalone localized javascript files for every culture and language. Creating a standard common javascript file for all cultures by sticking to Microsoft Ajax Library. For (1), we follow the same convention for views and resource files. For example, for the file “myscript.js”, you need to create “myscript.es-CL.js”, “myscript.ar-JO.js”, etc. We can reference the javascript files easily from our views by appending culture name to the javascript file :\n\u0026lt;script src=\"@Url.Content(\"~/Scripts/myscript\" + ViewBag._culture + \".js\")\" type=\"text/javascript\"\u0026gt;\u0026lt;/script\u0026gt; The variable “_culture” is already defined in the base controller and works nicely by ignoring default culture (returns null in this case).\nEven if you want to use Microsoft Ajax Library, you may still need separate javascript files that define text messages to the end user. You can define a literal object that contains the list of messages, or if you are using separate views for every culture, you can use inline javascript instead of separate javascript files.\nSummary Building a multilingual web application is not an easy task. but it’s worth it especially for web applications targeting users from all over the world, something which many sites do. It is true that globalization is not the first priority in site development process, however, it should be well planned early in the stage of development so it can be easily implemented in the future. Luckily, ASP.NET supports globalization and there are plenty of .NET classes that are handy. We have seen how to create an ASP.NET MVC 3 application that supports 3 different languages, including a right-to-left one, which requires a different UI layout. Anyway, here is a summary of how to globalize a site in ASP.NET MVC 3:\nAdd a base controller from which all controllers inherit. This controller will intercept the view names returned and will adjust them depending on the current culture set. Add a helper class that stores the list of culture names that the site will support. Create a single view or set of views for every culture and language. Create resource files that contain translation of all string messages. (e.g. Resources.resx, Resources.es-CL.resx, Resources.ar-JO.resx, etc ) Localize javascript files. ","date":"24 January 2012","externalUrl":null,"permalink":"/asp-net-mvc-3-internationalization/","section":"Articles","summary":"With MVC getting more popular each day and C# increasing the market share (Tiobe index) and your applications getting larger it is worth looking in to how to Internationalise your application, the source of all sources for internationalization is Guy Smith-Ferrier and his blog is a source of wealthy knowledge.\n","title":"ASP.NET MVC 3 Internationalization","type":"articles"},{"content":"Two great videos from Hillel Coren, a 20 minute crash course reviewing the essentials of computer programming.\nDon’t thank me thank Hillel\n","date":"23 January 2012","externalUrl":null,"permalink":"/essentials-of-computer-programming/","section":"Articles","summary":"Two great videos from Hillel Coren, a 20 minute crash course reviewing the essentials of computer programming.\nDon’t thank me thank Hillel\n","title":"Essentials of Computer Programming","type":"articles"},{"content":"I’ve been working with TFS for sometime and when you are using the process flows you need to understand how the workflows work with the work items types.\nThere are two main types I have worked with Agile and CMMI Process Improvements.\nI’m not an expert on these workflows but you can get access to the full guidance from:\nMSF for Agile Software Development Process Guidance MSF for CMMI Process Improvement or if you are really stuck go to Microsoft’s Process Templates and Tools page The diagrams below are taken from VSTS blog site, but you must remember thes eare just starting points and they can be changed to suit your own workflow within your business\nMSF for Agile Software Development featuring 5 work item types: Bug, Requirement, Quality of Service Requirement (QoS), Risk and Task.\nWork Item Type: Bug\nWork Item Type: Scenario\nWork Item Type: Quality of Service Requirement (also known as “technical requirement”)\nWork Item Type: Risk\nWork Item Type: Task\nMSF for CMMI Process Improvement featuring 7 work item types: Bug, Requirement, Change Request, Issue, Review, Risk, Task\nWork Item Type: Bug\nWork Item Type: Requirement\nWork Item Type: Change Request\nWork Item Type: Issue\nWork Item Type: Review\nWork Item Type: Risk\nWork Item Type: Task\n","date":"17 January 2012","externalUrl":null,"permalink":"/workflow-with-tfs/","section":"Articles","summary":"I’ve been working with TFS for sometime and when you are using the process flows you need to understand how the workflows work with the work items types.\nThere are two main types I have worked with Agile and CMMI Process Improvements.\n","title":"Workflow with TFS","type":"articles"},{"content":"When I come to amend a table in SQL Server all is fine until you come to save the new structure you end up getting the following message:\n“Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created.”\nThis is happening because ““Prevent saving changes that require table re-creation” option is enabled. You can disable this by going into Tools -\u0026gt; Options -\u0026gt; Designers-\u0026gt; Uncheck “Prevent saving changes that require table re-creation”, this is either in Visual Studio or SQL Management Studio.\nNow you can apply your new changes to the table\n","date":"17 January 2012","externalUrl":null,"permalink":"/amending-a-sql-table-without-getting-saving-changes-is-not-permitted/","section":"Articles","summary":"When I come to amend a table in SQL Server all is fine until you come to save the new structure you end up getting the following message:\n“Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created.”\n","title":"Amending a SQL table without getting “Saving changes is not permitted”","type":"articles"},{"content":"LINQ to SQL is a very easy to use and very powerful tool for many things when dealing with SQL. But the time has come that I need to wrap it all up and use an iRepository pattern. I’ve Googled for the IRepository and found a few useful references but none that will complete my picture. How ever I did get some good ideas when looking around othe rimplementation of the IRepository pattern that others had implmented.\nSo why whould I use the iRepository when Linq to Sql and so good?\nThere are a few time, and this keeps happening that when you come to save an object you forget to use the SubmitChanges(), and what happens if there is a conflict. You can handle conflicts in Linq to Sql but you need to add extra code for each time you SubmitChanges(). The iRepository I am going to use will wrap all this up and sort it out for us in to one place. There are a number of reasons, but mainly the iRepository will provide a layer that I can use to hold all these methods in one place.\nFirst the pattern will use Generics. So this means that you can passing in any Linq to Sql object and it will perform a task.\nSo here is the Interface I’ll be using:\npublic interface IRepository\u0026lt;T\u0026gt; where T : class { /// \u0026lt;summary\u0026gt; /// Return all instances of type T. /// \u0026lt;/summary\u0026gt; /// \u0026lt;returns\u0026gt;\u0026lt;/returns\u0026gt; IEnumerable\u0026lt;T\u0026gt; All(); /// \u0026amp;lt;summary\u0026amp;gt; /// Return all instances of type T that match the expression exp. /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;exp\u0026quot;\u0026amp;gt;\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; IEnumerable\u0026amp;lt;T\u0026amp;gt; FindAll(Func\u0026amp;lt;T, bool\u0026amp;gt; exp); /// \u0026amp;lt;summary\u0026amp;gt;Returns the single entity matching the expression. Throws an exception if there is not exactly one such entity.\u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;exp\u0026quot;\u0026amp;gt;\u0026amp;lt;/param\u0026amp;gt;\u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; T Single(Func\u0026amp;lt;T, bool\u0026amp;gt; exp); /// \u0026amp;lt;summary\u0026amp;gt;Returns the first element satisfying the condition.\u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;exp\u0026quot;\u0026amp;gt;\u0026amp;lt;/param\u0026amp;gt;\u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; T First(Func\u0026amp;lt;T, bool\u0026amp;gt; exp); /// \u0026amp;lt;summary\u0026amp;gt; /// Mark an entity to be deleted when the context is saved. /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;entity\u0026quot;\u0026amp;gt;\u0026amp;lt;/param\u0026amp;gt; void MarkForDeletion(T entity); /// \u0026amp;lt;summary\u0026amp;gt; /// Create a new instance of type T. /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; T CreateInstance(); /// \u0026amp;lt;summary\u0026amp;gt;Persist the data context.\u0026amp;lt;/summary\u0026amp;gt; void SaveAll(); long Count(Expression\u0026amp;lt;Func\u0026amp;lt;T, bool\u0026amp;gt;\u0026amp;gt; criteria); void Save(T entity); }\u0026lt;/pre\u0026gt; So that is the easy part, next is the concreate implementation of the interface\npublic class Repository\u0026lt;T\u0026gt; : IRepository\u0026lt;T\u0026gt; where T : class { protected DataContext DataContext; /// \u0026amp;lt;summary\u0026amp;gt; /// Return all instances of type T. /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; public IEnumerable\u0026amp;lt;T\u0026amp;gt; All() { return GetTable; } /// \u0026amp;lt;summary\u0026amp;gt; /// Return all instances of type T that match the expression exp. /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;exp\u0026quot;\u0026amp;gt;\u0026amp;lt;/param\u0026amp;gt; /// \u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; public IEnumerable\u0026amp;lt;T\u0026amp;gt; FindAll(Func\u0026amp;lt;T, bool\u0026amp;gt; exp) { return GetTable.Where(exp); } /// \u0026amp;lt;summary\u0026amp;gt;See _vertexRepository.\u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;exp\u0026quot;\u0026amp;gt;\u0026amp;lt;/param\u0026amp;gt;\u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; public T Single(Func\u0026amp;lt;T, bool\u0026amp;gt; exp) { return GetTable.SingleOrDefault(exp); } /// \u0026amp;lt;summary\u0026amp;gt;See _vertexRepository.\u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;exp\u0026quot;\u0026amp;gt;\u0026amp;lt;/param\u0026amp;gt;\u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; public T First(Func\u0026amp;lt;T, bool\u0026amp;gt; exp) { return GetTable.First(exp); } /// \u0026amp;lt;summary\u0026amp;gt;See _vertexRepository.\u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;param name=\u0026quot;entity\u0026quot;\u0026amp;gt;\u0026amp;lt;/param\u0026amp;gt; public virtual void MarkForDeletion(T entity) { DataContext.GetTable\u0026amp;lt;T\u0026amp;gt;().DeleteOnSubmit(entity); } /// \u0026amp;lt;summary\u0026amp;gt; /// Create a new instance of type T. /// \u0026amp;lt;/summary\u0026amp;gt; /// \u0026amp;lt;returns\u0026amp;gt;\u0026amp;lt;/returns\u0026amp;gt; public virtual T CreateInstance() { var entity = Activator.CreateInstance\u0026amp;lt;T\u0026amp;gt;(); GetTable.InsertOnSubmit(entity); return entity; } /// \u0026amp;lt;summary\u0026amp;gt;See _vertexRepository.\u0026amp;lt;/summary\u0026amp;gt; public void SaveAll() { DataContext.SubmitChanges(); } public long Count(Expression\u0026amp;lt;Func\u0026amp;lt;T, bool\u0026amp;gt;\u0026amp;gt; exp) { return GetTable.Where(exp).Count(); } public void Save(T entity) { Save(new List\u0026amp;lt;T\u0026amp;gt; { entity }); return; } public void Save(IEnumerable\u0026amp;lt;T\u0026amp;gt; entities) { var table = DataContext.GetTable\u0026amp;lt;T\u0026amp;gt;(); foreach (var entity in entities) { var entity1 = entity; var dbEntity = (from p in table where p == entity1 select p).FirstOrDefault(); if (dbEntity == null) table.InsertOnSubmit(entity); try { // Save the changes. DataContext.SubmitChanges(); } // Detect concurrency conflicts. catch (ChangeConflictException) { // Resolve conflicts. DataContext.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges); } } } public Repository(DataContext dataContext) { DataContext = dataContext; } #region Properties private Table\u0026amp;lt;T\u0026amp;gt; GetTable { get { return DataContext.GetTable\u0026amp;lt;T\u0026amp;gt;(); } } #endregion }\u0026lt;/pre\u0026gt; That is it, job done.\nYou’ll notice that in the Save method it handles quite a lot from inserting a new record, updating an exisiting record if one is found with the addition of an object copier to make life easier and then will save the changes to the database and if there happens to be any conflicts it deals with them.\nThe Save() will accept either single objects or and IEnumerable of an object making things easier and simpler.\nI would love any feed back on what I have produced\nTo compliment the IRepository concreate class I’ve built a set of tests using MS Test that create and use a test database:\nIRepository.zip (4.11 kb)\nIRepository.Tests.zip (47.25 kb)\n","date":"17 January 2012","externalUrl":null,"permalink":"/ilinqrepository-at-last/","section":"Articles","summary":"LINQ to SQL is a very easy to use and very powerful tool for many things when dealing with SQL. But the time has come that I need to wrap it all up and use an iRepository pattern. I’ve Googled for the IRepository and found a few useful references but none that will complete my picture. How ever I did get some good ideas when looking around othe rimplementation of the IRepository pattern that others had implmented.\n","title":"ILinqRepository at last","type":"articles"},{"content":"If you are like me and us are using an IRepository for Linq to SQL you’ll probably at some point need to be able to generate a Transaction.\nAs the IRepository saves records as it goes and not on a SubmitChanges() we’re going to have to use the Microsoft TransactionScope Class, from the System.Transactions (in System.Transactions.dll), which makes a code block transactional.\nHere it is:\nusing (var transaction = new TransactionScope()) { try { //Do something here transaction.Complete(); } catch (Exception ex) { return; } }\nIt is also worth having a look at Implementing an Implicit Transaction using Transaction Scoping for further information on what you can do.\nAfter playing with this for a while I found that you some times get a MSDTC error, to fixes this take a look at:\nFix MSDTC (Microsoft Distributed transaction coordinator) by Pongsathon Keng\n","date":"16 January 2012","externalUrl":null,"permalink":"/transaction-scoping-within-linq-to-sql/","section":"Articles","summary":"If you are like me and us are using an IRepository for Linq to SQL you’ll probably at some point need to be able to generate a Transaction.\nAs the IRepository saves records as it goes and not on a SubmitChanges() we’re going to have to use the Microsoft TransactionScope Class, from the System.Transactions (in System.Transactions.dll), which makes a code block transactional.\n","title":"Transaction scoping within Linq to Sql","type":"articles"},{"content":"Ever used Google Mail and the search when trying to find something and it can’t find it. This is most probably because it is somewhere where the default search does not look in, like the BIN\nTo search everywhere you use in:anywhere\nTo see all the the possibilities of search in Google Mail check out:\nhttp://support.google.com/mail/bin/answer.py?hl=en\u0026amp;answer=7190\n","date":"16 December 2011","externalUrl":null,"permalink":"/google-mail-not-searching-everywhere/","section":"Articles","summary":"Ever used Google Mail and the search when trying to find something and it can’t find it. This is most probably because it is somewhere where the default search does not look in, like the BIN\n","title":"Google Mail not searching everywhere","type":"articles"},{"content":"Found this quick reference for Rhino Mocks (3.3), very useful\nRhino Mocks 3.3 Quick Reference.pdf (261.98 kb)\n","date":"15 December 2011","externalUrl":null,"permalink":"/rhino-mocks-quick-reference/","section":"Articles","summary":"Found this quick reference for Rhino Mocks (3.3), very useful\nRhino Mocks 3.3 Quick Reference.pdf (261.98 kb)\n","title":"Rhino Mocks quick reference","type":"articles"},{"content":"So I need to trap and look at the traffic going over HTTP and knowing that Firefox is the browser to use with all it different plugins it makes sense to download the latest version of Firefox and see what I can plug in to it.\nWhat I like about Firefox is it is so easy to install plugins, just click restart Firefox and you’re done.\nSo what I need to do is trap, monitor and post HTTP requests using XML, so what plug in am I going to use?\nFirst one is FireBug every good developer and bad developer, even hackers will be using FireBug.\nNext I need to monitor what is happening and I found Tamper Data which monitors ongoing requests, and more importantly monitors and posts and gets in the back ground.\nOkay now the more tricky issue of being about to POST or GET using HTTP, I settled for Poster a great plug in for all the REST requests and perfect for what I am looking for.\nSo to summerise here is a list of what I have downloaded:\nFirefox FireBug Tamper Data Poster So I’m off, if I get any problems with them I’mm report them directly on this blog with comments so if you see no comments all is good.\n","date":"9 December 2011","externalUrl":null,"permalink":"/debugging-and-developing-using-firefox/","section":"Articles","summary":"So I need to trap and look at the traffic going over HTTP and knowing that Firefox is the browser to use with all it different plugins it makes sense to download the latest version of Firefox and see what I can plug in to it.\n","title":"Debugging and developing using Firefox","type":"articles"},{"content":"So I’m back and ready to go, with just getting back from my travelling I’m back at work with only two days of my own time….! Oh well I was looking at taking December off and start fully working in the new year. Not that I took the first job that came along, far from it. While on the beaches of Goa I made up a list of what work I will only accept it included working near where I live, work I have done before so as to make it easier to get back in to the working mode, something to do with the Olympics, and a small team on a new project. And you guessed it this role fits all the criteria so a result So time to keep my blog up to date and running again……!\n","date":"9 December 2011","externalUrl":null,"permalink":"/back-and-working/","section":"Articles","summary":"So I’m back and ready to go, with just getting back from my travelling I’m back at work with only two days of my own time….! Oh well I was looking at taking December off and start fully working in the new year. Not that I took the first job that came along, far from it. While on the beaches of Goa I made up a list of what work I will only accept it included working near where I live, work I have done before so as to make it easier to get back in to the working mode, something to do with the Olympics, and a small team on a new project. And you guessed it this role fits all the criteria so a result ","title":"Back and working","type":"articles"},{"content":"Time comes when you have a database running, fully deployed and working, and a few years later something appears to be going wrong but you are not sure what or what is happening.\nYou start looking at possible options, and one of the first that springs to mind is performing an audit on any changed information, wouldn’t it be nice to be able to audit information so that you can see what an when things are changing?\nOne way of doing this is to use triggers with inside of SQL Server, this does come at a high cost, but does provide you with the information you require.\nFirst we need to have a Audit table\nCREATE TABLE [dbo].[Audit](\n[AuditID] [int] IDENTITY(1,1) NOT NULL,\n[Type] [char](1) NULL,\n[TableName] [varchar](128) NULL,\n[PrimaryKeyField] [varchar](1000) NULL,\n[PrimaryKeyValue] [varchar](1000) NULL,\n[FieldName] [varchar](128) NULL,\n[OldValue] [varchar](1000) NULL,\n[NewValue] [varchar](1000) NULL,\n[UpdateDate] [datetime] NULL DEFAULT (getdate()),\n[UserName] [varchar](128) NULL\n) ON [PRIMARY]\nOkay now that is done, then we need to decide on what triggers we want, we could place a trigger on all the tables, like this:\nDECLARE @sql varchar(8000), @TABLE_NAME sysname\nSET NOCOUNT ON\nSELECT @TABLE_NAME= MIN(TABLE_NAME)\nFROM INFORMATION_SCHEMA.Tables\nWHERE\nTABLE_TYPE= 'BASE TABLE'\nAND TABLE_NAME!= 'sysdiagrams'\nAND TABLE_NAME!= 'Audit'\nWHILE @TABLE_NAME IS NOT NULL\nBEGIN\nEXEC('IF OBJECT_ID (''' + @TABLE_NAME+ '_ChangeTracking'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME+ '_ChangeTracking')\nSELECT @sql =\n'\ncreate trigger ' + @TABLE_NAME+ '_ChangeTracking on ' + @TABLE_NAME+ ' for insert, update, delete\nas\ndeclare @bit int ,\n@field int ,\n@maxfield int ,\n@char int ,\n@fieldname varchar(128) ,\n@TableName varchar(128) ,\n@PKCols varchar(1000) ,\n@sql varchar(2000),\n@UpdateDate varchar(21) ,\n@UserName varchar(128) ,\n@Type char(1) ,\n@PKFieldSelect varchar(1000),\n@PKValueSelect varchar(1000)\nselect @TableName = ''' + @TABLE_NAME+ '''\n-- date and user\nselect @UserName = system_user ,\n@UpdateDate = convert(varchar(8), getdate(), 112) + '' '' + convert(varchar(12), getdate(), 114)\n-- Action\nif exists (select * from inserted)\nif exists (select * from deleted)\nselect @Type = ''U''\nelse\nselect @Type = ''I''\nelse\nselect @Type = ''D''\n-- get list of columns\nselect * into #ins from inserted\nselect * into #del from deleted\n-- Get primary key columns for full outer join\nselect @PKCols = coalesce(@PKCols + '' and'', '' on'') + '' i.'' + c.COLUMN_NAME + '' = d.'' + c.COLUMN_NAME\nfrom INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,\nINFORMATION_SCHEMA.KEY_COLUMN_USAGE c\nwhere pk.TABLE_NAME = @TableName\nand CONSTRAINT_TYPE = ''PRIMARY KEY''\nand c.TABLE_NAME = pk.TABLE_NAME\nand c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME\n-- Get primary key fields select for insert\nselect @PKFieldSelect = coalesce(@PKFieldSelect+''+'','''') + '''''''' + COLUMN_NAME + ''''''''\nfrom INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,\nINFORMATION_SCHEMA.KEY_COLUMN_USAGE c\nwhere pk.TABLE_NAME = @TableName\nand CONSTRAINT_TYPE = ''PRIMARY KEY''\nand c.TABLE_NAME = pk.TABLE_NAME\nand c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME\nselect\n@PKValueSelect = coalesce(@PKValueSelect+''+'','''') + ''convert(varchar(100), coalesce(i.'' + COLUMN_NAME + '',d.'' + COLUMN_NAME + ''))''\nfrom INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk , INFORMATION_SCHEMA.KEY_COLUMN_USAGE c where pk.TABLE_NAME = @TableName and CONSTRAINT_TYPE = ''PRIMARY KEY'' and c.TABLE_NAME = pk.TABLE_NAME and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME\nif @PKCols is null\nbegin\nraiserror(''no PK on table %s'', 16, -1, @TableName)\nreturn\nend\nselect @field = 0, @maxfield = max(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName\nwhile @field \u0026lt; @maxfield\nbegin\nselect\n@field = min(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName and ORDINAL_POSITION \u0026gt; @field\nselect @bit = (@field - 1 )% 8 + 1\nselect @bit = power(2,@bit - 1)\nselect @char = ((@field - 1) / 8) + 1\nif substring(COLUMNS_UPDATED(),@char, 1) \u0026amp; @bit \u0026gt; 0 or @Type in (''I'',''D'')\nbegin\nselect @fieldname = COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName and ORDINAL_POSITION = @field\nselect\n@sql = ''insert Audit (Type, TableName, PrimaryKeyField, PrimaryKeyValue, FieldName, OldValue, NewValue, UpdateDate, UserName)''\nselect @sql = @sql + '' select '''''' + @Type + ''''''''\nselect @sql = @sql + '','''''' + @TableName + ''''''''\nselect @sql = @sql + '','' + @PKFieldSelect\nselect @sql = @sql + '','' + @PKValueSelect\nselect @sql = @sql + '','''''' + @fieldname + ''''''''\nselect @sql = @sql + '',convert(varchar(1000),d.'' + @fieldname + '')''\nselect @sql = @sql + '',convert(varchar(1000),i.'' + @fieldname + '')''\nselect @sql = @sql + '','''''' + @UpdateDate + ''''''''\nselect @sql = @sql + '','''''' + @UserName + ''''''''\nselect @sql = @sql + '' from #ins i full outer join #del d''\nselect @sql = @sql + @PKCols\nselect @sql = @sql + '' where i.'' + @fieldname + '' \u0026lt;\u0026gt; d.'' + @fieldname\nselect @sql = @sql + '' or (i.'' + @fieldname + '' is null and d.'' + @fieldname + '' is not null)''\nselect @sql = @sql + '' or (i.'' + @fieldname + '' is not null and d.'' + @fieldname + '' is null)''\nexec (@sql)\nend\nend\n'\nSELECT @sql\nEXEC(@sql)\nSELECT @TABLE_NAME= MIN(TABLE_NAME) FROM INFORMATION_SCHEMA.Tables\nWHERE TABLE_NAME\u0026gt; @TABLE_NAME\nAND TABLE_TYPE= 'BASE TABLE'\nAND TABLE_NAME!= 'sysdiagrams'\nAND TABLE_NAME!= 'Audit'\nEND\nor just a selected table\nDECLARE @TABLE varchar(1000)\nSET @TABLE = 'table name to audit'\nDECLARE @sql varchar(8000), @TABLE_NAME sysname\nSET NOCOUNT ON\nSELECT @TABLE_NAME= MIN(TABLE_NAME)\nFROM INFORMATION_SCHEMA.Tables\nWHERE\nTABLE_TYPE= 'BASE TABLE'\nAND Table_Name = @TABLE\nWHILE @TABLE_NAME IS NOT NULL\nBEGIN\nEXEC('IF OBJECT_ID (''' + @TABLE_NAME+ '_ChangeTracking'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME+ '_ChangeTracking')\nSELECT @sql =\n'\ncreate trigger ' + @TABLE_NAME+ '_ChangeTracking on ' + @TABLE_NAME+ ' for insert, update, delete\nas\ndeclare @bit int ,\n@field int ,\n@maxfield int ,\n@char int ,\n@fieldname varchar(128) ,\n@TableName varchar(128) ,\n@PKCols varchar(1000) ,\n@sql varchar(2000),\n@UpdateDate varchar(21) ,\n@UserName varchar(128) ,\n@Type char(1) ,\n@PKFieldSelect varchar(1000),\n@PKValueSelect varchar(1000)\nselect @TableName = ''' + @TABLE_NAME+ '''\n-- date and user\nselect @UserName = system_user ,\n@UpdateDate = convert(varchar(8), getdate(), 112) + '' '' + convert(varchar(12), getdate(), 114)\n-- Action\nif exists (select * from inserted)\nif exists (select * from deleted)\nselect @Type = ''U''\nelse\nselect @Type = ''I''\nelse\nselect @Type = ''D''\n-- get list of columns\nselect * into #ins from inserted\nselect * into #del from deleted\n-- Get primary key columns for full outer join\nselect @PKCols = coalesce(@PKCols + '' and'', '' on'') + '' i.'' + c.COLUMN_NAME + '' = d.'' + c.COLUMN_NAME\nfrom INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,\nINFORMATION_SCHEMA.KEY_COLUMN_USAGE c\nwhere pk.TABLE_NAME = @TableName\nand CONSTRAINT_TYPE = ''PRIMARY KEY''\nand c.TABLE_NAME = pk.TABLE_NAME\nand c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME\n-- Get primary key fields select for insert\nselect @PKFieldSelect = coalesce(@PKFieldSelect+''+'','''') + '''''''' + COLUMN_NAME + ''''''''\nfrom INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,\nINFORMATION_SCHEMA.KEY_COLUMN_USAGE c\nwhere pk.TABLE_NAME = @TableName\nand CONSTRAINT_TYPE = ''PRIMARY KEY''\nand c.TABLE_NAME = pk.TABLE_NAME\nand c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME\nselect\n@PKValueSelect = coalesce(@PKValueSelect+''+'','''') + ''convert(varchar(100), coalesce(i.'' + COLUMN_NAME + '',d.'' + COLUMN_NAME + ''))''\nfrom INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk , INFORMATION_SCHEMA.KEY_COLUMN_USAGE c where pk.TABLE_NAME = @TableName and CONSTRAINT_TYPE = ''PRIMARY KEY'' and c.TABLE_NAME = pk.TABLE_NAME and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME\nif @PKCols is null\nbegin\nraiserror(''no PK on table %s'', 16, -1, @TableName)\nreturn\nend\nselect @field = 0, @maxfield = max(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName\nwhile @field \u0026lt; @maxfield\nbegin\nselect\n@field = min(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName and ORDINAL_POSITION \u0026gt; @field\nselect @bit = (@field - 1 )% 8 + 1\nselect @bit = power(2,@bit - 1)\nselect @char = ((@field - 1) / 8) + 1\nif substring(COLUMNS_UPDATED(),@char, 1) \u0026amp; @bit \u0026gt; 0 or @Type in (''I'',''D'')\nbegin\nselect @fieldname = COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @TableName and ORDINAL_POSITION = @field\nselect\n@sql = ''insert Audit (Type, TableName, PrimaryKeyField, PrimaryKeyValue, FieldName, OldValue, NewValue, UpdateDate, UserName)''\nselect @sql = @sql + '' select '''''' + @Type + ''''''''\nselect @sql = @sql + '','''''' + @TableName + ''''''''\nselect @sql = @sql + '','' + @PKFieldSelect\nselect @sql = @sql + '','' + @PKValueSelect\nselect @sql = @sql + '','''''' + @fieldname + ''''''''\nselect @sql = @sql + '',convert(varchar(1000),d.'' + @fieldname + '')''\nselect @sql = @sql + '',convert(varchar(1000),i.'' + @fieldname + '')''\nselect @sql = @sql + '','''''' + @UpdateDate + ''''''''\nselect @sql = @sql + '','''''' + @UserName + ''''''''\nselect @sql = @sql + '' from #ins i full outer join #del d''\nselect @sql = @sql + @PKCols\nselect @sql = @sql + '' where i.'' + @fieldname + '' \u0026lt;\u0026gt; d.'' + @fieldname\nselect @sql = @sql + '' or (i.'' + @fieldname + '' is null and d.'' + @fieldname + '' is not null)''\nselect @sql = @sql + '' or (i.'' + @fieldname + '' is not null and d.'' + @fieldname + '' is null)''\nexec (@sql)\nend\nend\n'\nSELECT @sql\nEXEC(@sql)\nSELECT @TABLE_NAME= MIN(TABLE_NAME) FROM INFORMATION_SCHEMA.Tables\nWHERE TABLE_NAME\u0026gt; @TABLE_NAME\nAND TABLE_TYPE= 'BASE TABLE'\nAND Table_Name = @TABLE\nEND\nOf course you need someway of turning off the triggers, so here you are:\nDECLARE @sql varchar(8000), @TABLE_NAME sysname\nSET NOCOUNT ON\nSELECT @TABLE_NAME= MIN(TABLE_NAME)\nFROM INFORMATION_SCHEMA.Tables\nWHERE\nTABLE_TYPE= 'BASE TABLE'\nAND TABLE_NAME!= 'sysdiagrams'\nAND TABLE_NAME!= 'Audit'\nWHILE @TABLE_NAME IS NOT NULL\nBEGIN\nEXEC('IF OBJECT_ID (''' + @TABLE_NAME+ '_ChangeTracking'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME+ '_ChangeTracking')\nSELECT @sql =\n'\nDROP trigger ' + @TABLE_NAME+ '_ChangeTracking'\nSELECT @sql\nEXEC(@sql)\nSELECT @TABLE_NAME= MIN(TABLE_NAME) FROM INFORMATION_SCHEMA.Tables\nWHERE TABLE_NAME\u0026gt; @TABLE_NAME\nAND TABLE_TYPE= 'BASE TABLE'\nAND TABLE_NAME!= 'sysdiagrams'\nAND TABLE_NAME!= 'Audit'\nEND\nThat should do it, I got the majority of SQL from Jon Galloway post Adding simple trigger-based auditing to your SQL Server database, so I can;t take all the credit for these scripts, just the changes and modifications.\nIf performance is an issue they you could check out Centralized Asynchronous Auditing with Service Broker or Centralized Asynchronous Auditing across Instances and Servers with Service Broker\n","date":"17 September 2010","externalUrl":null,"permalink":"/audit-information-with-sql/","section":"Articles","summary":"Time comes when you have a database running, fully deployed and working, and a few years later something appears to be going wrong but you are not sure what or what is happening.\nYou start looking at possible options, and one of the first that springs to mind is performing an audit on any changed information, wouldn’t it be nice to be able to audit information so that you can see what an when things are changing?\n","title":"Audit information with SQL","type":"articles"},{"content":"\n","date":"1 July 2010","externalUrl":null,"permalink":"/dilbet/","section":"Articles","summary":"\n","title":"Dilbet","type":"articles"},{"content":"Found a nice simple page to generate a Loading Images, simple to use and so easy to generate the image that you need\nhttp://www.ajaxload.info/\n","date":"28 June 2010","externalUrl":null,"permalink":"/spinning-image-for-loading-a-page/","section":"Articles","summary":"Found a nice simple page to generate a Loading Images, simple to use and so easy to generate the image that you need\nhttp://www.ajaxload.info/\n","title":"Spinning image for loading a page","type":"articles"},{"content":"With HTML5 becoming more of the norm, well if it’s not it is about to be, and IE6 not supporting it (hang on IE9 does not currently support it either!), so it will just have to be dumped, at last 🙂 As us developers will need to get up to speed on HTML5 there is a new resource available from Google, HTML5Rocks, lots of great resource and information available on this site\n","date":"23 June 2010","externalUrl":null,"permalink":"/are-you-ready-for-html5/","section":"Articles","summary":"With HTML5 becoming more of the norm, well if it’s not it is about to be, and IE6 not supporting it (hang on IE9 does not currently support it either!), so it will just have to be dumped, at last 🙂 As us developers will need to get up to speed on HTML5 there is a new resource available from Google, HTML5Rocks, lots of great resource and information available on this site\n","title":"Are you ready for HTML5","type":"articles"},{"content":"I have had a few people saying that LINQ to SQL is hard to use for Separation of Concerns, so I’ve created a small project that show how to do it. I have used the MEF as my SoC framework.\nProject is using .Net 3.5\nSoCLINQ2SQL.zip (905.61 kb)\nTo enhance this it is worth look at Mike Hadlow post of Repository.GetById using LINQ Expression Syntax\n","date":"23 June 2010","externalUrl":null,"permalink":"/linq-to-sql-using-soc/","section":"Articles","summary":"I have had a few people saying that LINQ to SQL is hard to use for Separation of Concerns, so I’ve created a small project that show how to do it. I have used the MEF as my SoC framework.\n","title":"LINQ to SQL using SoC","type":"articles"},{"content":" If you are trying to use MEF with open generic types like:\n[Export(typeof(IRepository\u0026lt;\u0026gt;))]\npublic class itial; padding: 0px; margin: 0px; border: 0px initial initial;\"\u0026gt;Repository\u0026lt;T\u0026gt; : IRepository\u0026lt;al; background-color: transparent; color: black; background-position: initial initial; background-repeat: initial initial; padding: 0px; margin: 0px; border: 0px initial initial;\"\u0026gt;T\u0026gt;\nwhere T : class\n{\nWith an import of\n[Import(typeof(IRepository\u0026lt;\u0026gt;))]\nprivate IRepository\u0026lt;Contact\u0026gt; repository;\nYou’ll come stuck, as the current implementation MEF does not support Open Generic Types.\nFor more information take a look at Glenn Block article Why doesn’t MEF support open-generics for exports? Because MEF is not type based\nAlso there is Open-generic support in the MEF Contrib, which can be found on codeplex.\nThe reasoning is this, MEF parts relate on contracts which are strings, not types. To illustrate, see the code below.\nnamespace Orders {\npublic interface IOrderRepository {}\n[Export(typeof(IOrderRespository))]\npublic class OrderRepository : IOrderRepository {\n}\n}\nAlthough I have passed typeof(IOrderRepsitory) to the export, that is just a convenience that gets converted to a contract name of “Orders.IOrderRepository”. The same applies to the importer…\n[Export]\npublic class OrderService(\n[Import]\npublic IOrderRepository Repository {gets;set;} )\nThe import on IOrderRepository also gets converted to a contract name of “Orders.IOrderRepository”. This way the container is able to satisfy the import as the 2 contracts match. In the same way we support closed generics, so….\npublic interface IRepository\u0026lt;T\u0026gt; {}\nnamespace Orders {\n[Export(typeof(IRepository\u0026lt;Order\u0026gt;))]\npublic class OrderRepository : IRepository\u0026lt;Order\u0026gt; {\n}\n}\n[Export]\npublic class OrderService(\n[Import]\npublic IRepository\u0026lt;Order\u0026gt; Repository {gets;set;} )\nWill work because the OrderRepository is exporting the contractname “Orders.IRepository\u0026lt;Order\u0026gt;” and the OrderService is importing the same contract.\nHowever, this is what it looks like if we try the same with open generics.\npublic interface IRepository\u0026lt;T\u0026gt; {}\nnamespace Utils {\n[Export(typeof(IRepository\u0026lt;\u0026gt;))]\npublic class Repository : IRepository\u0026lt;T\u0026gt; {\n}\n}\n[Export]\npublic class OrderService(\n[Import]\npublic IRepository\u0026lt;Order\u0026gt; Repository {gets;set;} Now the contract names will be different. The exporter will have a contract of “Utils.IRepository\u0026lt;\u0026gt;” and the importer will have a contract of “Utils.IRepository\u0026lt;Order\u0026gt;”.\nIt is a simple match up, that breaks down in the open-generics case. This is because fundamentally, MEF is not matching on type.\nOriginal article form codeplex\n","date":"23 June 2010","externalUrl":null,"permalink":"/mef-not-supporting-open-generic-types/","section":"Articles","summary":" If you are trying to use MEF with open generic types like:\n","title":"MEF not supporting open generic types","type":"articles"},{"content":"You may or may not have come across the ability within LINQ to SQL to have mapping to and from your own objects.\nMicrosoft has a mapping builder called sqlmetal, which is a code generation tool to generate the mapping automatically.\nHere is a sample command line to generate the mapping file.\nsqlmetal /server:. /database:mydb /map:mydbMappings.xml /code:code.dbml\n","date":"22 June 2010","externalUrl":null,"permalink":"/how-to-generate-linq-to-sql-mapping/","section":"Articles","summary":"You may or may not have come across the ability within LINQ to SQL to have mapping to and from your own objects.\nMicrosoft has a mapping builder called sqlmetal, which is a code generation tool to generate the mapping automatically.\n","title":"How to generate LINQ to SQL Mapping","type":"articles"},{"content":"While using Gallio for performing Unit Tests within Visual Studio, I have noticed that some times you can’t run Unit Tests, or it says that no tests available, with thanks to Lee, he pointed me to a simple fix\nVisual Studio can be used to run your tests in process, with the debugger. In order for a project to be “testable”, you’ll need to make sure it has the following in the csproj:\n\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;\u0026amp;lt;ProjectTypeGuids\u0026amp;gt;{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\u0026amp;lt;/ProjectTypeGuids\u0026amp;gt;\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; ","date":"22 June 2010","externalUrl":null,"permalink":"/running-gallio-tests-within-visual-studio/","section":"Articles","summary":"While using Gallio for performing Unit Tests within Visual Studio, I have noticed that some times you can’t run Unit Tests, or it says that no tests available, with thanks to Lee, he pointed me to a simple fix\n","title":"Running Gallio tests within Visual Studio","type":"articles"},{"content":"I recently purchased a Pertec i-Disk Bullet 32Gb, and within a hour I had broken it, it had become write protected, not sure why. After an e-mail to Pertec support they sent me a solution to solve the problem, here is what they said and how to get your i-Disk working again\nPlease use USB flash drive recovery tool as attach file. And repair unworkable i-Disk Bulletproof as following procedures;\nIf this utility still can’t help you to repair your failure Bulletproof USB, we suggest you can send back the USB to original purchased store/vendor,\nThey will provide you RMA service for further check and repair process.\nURescue utility repairing procedures:\n1. Backup your personal data stored in i-Disk Bulletproof if available.\n2. Plug unworkable i-Disk Bulletproof into a safety virus-free desktop or notebook computer.\n3. Execute “URescue.exe”, click “Update” button to repair i-Disk Bulletproof.\n4. Please be remind, all data stored in i-Disk Bulletproof will be deleted. Click “OK” to continue.\n5. Repair successfully, click “OK” to exit URescue utility.\nURescue.zip (5.31 mb)\n","date":"18 June 2010","externalUrl":null,"permalink":"/pretec-i-disk-how-to-rescue/","section":"Articles","summary":"I recently purchased a Pertec i-Disk Bullet 32Gb, and within a hour I had broken it, it had become write protected, not sure why. After an e-mail to Pertec support they sent me a solution to solve the problem, here is what they said and how to get your i-Disk working again\n","title":"PRETEC i-DISK – how to rescue","type":"articles"},{"content":"I have just given an hour presentation on AutoMapper, and great Object to Object mapper.\nHere is the source file with the samples\nAutoMapper.zip (855.99 kb)\n","date":"18 June 2010","externalUrl":null,"permalink":"/automapper/","section":"Articles","summary":"I have just given an hour presentation on AutoMapper, and great Object to Object mapper.\nHere is the source file with the samples\nAutoMapper.zip (855.99 kb)\n","title":"AutoMapper","type":"articles"},{"content":"If you have an object that contains a List or IList, and you need to convert it in to a Collection, here is how you can do it in a single line.\nvar foo = new Collection\u0026lt;FooList\u0026gt;(fooList);\n","date":"17 June 2010","externalUrl":null,"permalink":"/convert-a-list-in-to-a-collection/","section":"Articles","summary":"If you have an object that contains a List or IList, and you need to convert it in to a Collection, here is how you can do it in a single line.\nvar foo = new Collection\u003cFooList\u003e(fooList);\n","title":"Convert a List in to a Collection","type":"articles"},{"content":"\n","date":"16 June 2010","externalUrl":null,"permalink":"/dependencies/","section":"Articles","summary":"\n","title":"Dependencies","type":"articles"},{"content":"The time will come when you are serializing and deserializing object to and from XML that you will come across nullable dates, or more correctly an attribute XML date that is nullable. If you are like me and using the System.Xml.Serialization namespace, which make the complete process of serializing and deserializing so much easier.\nHere is the issue, the code below is a nullable datetime, which is fine in .NET\nprivate DateTime? dob;\n[XmlAttribute]\npublic DateTime? DOB\n{\nget\n{\nreturn dob;\n}\nset\n{\ndob = value;\n}\n}\nWhen you come the serialize/deserialize you find you get an error of:\nSystem.InvalidOperationException: Cannot serialize member ‘DOB’ of type System.Nullable`1[System.DateTime]. XmlAttribute/XmlText cannot be used to encode complex types.\nSo to over come this you have a number of options, the one I have come up with is to pull the date in using a string and then pre-process the date and then store it in to the nullable date field, like this:\nprivate DateTime? dob;\n[XmlIgnore]\npublic DateTime? DOB\n{\nget\n{\nreturn dob;\n}\nset\n{\ndob = value;\n}\n}\n[XmlAttribute(“DOB”)]\npublic string DoBstring\n{\nget { return DOB.HasValue\n? XmlConvert.ToString(DOB.Value, XmlDateTimeSerializationMode.Unspecified)\n: string.Empty;\n}\nset { DOB = !string.IsNullOrEmpty(value)\n? XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Unspecified)\n: (DateTime?) null;\n}\n}\nYou notice that the nullable Date field is not decorated with an XmlIgnore attribute, and the string is picking up the DOB attribute tag\n","date":"11 June 2010","externalUrl":null,"permalink":"/how-to-serializedeserialize-a-nullable-date/","section":"Articles","summary":"The time will come when you are serializing and deserializing object to and from XML that you will come across nullable dates, or more correctly an attribute XML date that is nullable. If you are like me and using the System.Xml.Serialization namespace, which make the complete process of serializing and deserializing so much easier.\n","title":"How to serialize/deserialize a nullable date","type":"articles"},{"content":"When using a Continuous Integration server such as TeamCity, you’ll need to be able to perform the ability to run tests, the easiest and most controlled way is by writing your own MSBuild Script.\nHere is a little build script that finds all the test files and then runs them using Gallio, of course you need to reference the Gallio MSBuildTasks, in my case they are in C:\\Program Files\\Gallio\\bin\\Gallio.MsBuildTasks.dll\n\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;\u0026amp;nbsp;\u0026amp;nbsp; \u0026amp;nbsp; \u0026amp;nbsp; \u0026amp;lt;!-- Finds test DLL's --\u0026amp;gt;\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;\u0026amp;nbsp;\u0026amp;nbsp; \u0026amp;nbsp; \u0026amp;nbsp;\u0026amp;lt;CreateItem Include=\"$(ProjectDirectory)/**/bin/debug/*.Test.dll\"\u0026amp;gt;\u0026lt;br /\u0026gt;\u0026amp;nbsp;\u0026amp;nbsp; \u0026amp;nbsp; \u0026amp;nbsp; \u0026amp;nbsp;\u0026amp;lt;Output TaskParameter=\"Include\" ItemName=\"TestFiles\"/\u0026amp;gt;\u0026lt;br /\u0026gt;\u0026amp;nbsp;\u0026amp;nbsp; \u0026amp;nbsp; \u0026amp;nbsp;\u0026amp;lt;/CreateItem\u0026amp;gt;\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;\u0026amp;nbsp;\u0026amp;nbsp; \u0026amp;nbsp; \u0026amp;nbsp;\u0026amp;lt;!-- Runs Tests --\u0026amp;gt;\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;\u0026amp;nbsp;\u0026amp;nbsp; \u0026amp;nbsp; \u0026amp;nbsp;\u0026amp;lt;Gallio IgnoreFailures=\"true\" Files=\"@(TestFiles)\"\u0026amp;gt;\u0026lt;br /\u0026gt;\u0026amp;nbsp;\u0026amp;nbsp; \u0026amp;nbsp; \u0026amp;nbsp; \u0026amp;nbsp;\u0026amp;lt;Output TaskParameter=\"ExitCode\" PropertyName=\"ExitCode\" /\u0026amp;gt;\u0026lt;br /\u0026gt;\u0026amp;nbsp;\u0026amp;nbsp; \u0026amp;nbsp; \u0026amp;nbsp;\u0026amp;lt;/Gallio\u0026amp;gt;\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt;\u0026amp;nbsp;\u0026amp;nbsp; \u0026amp;nbsp; \u0026amp;nbsp;\u0026amp;lt;Error Text=\"Tests execution failed\" Condition=\" '$(ExitCode)' != 0 And '@(TestFiles)' != '' \" /\u0026amp;gt;\u0026lt;/p\u0026gt; \u0026lt;p\u0026gt; BuildAndTest.msbuild (3.32 kb)\n","date":"7 June 2010","externalUrl":null,"permalink":"/running-gallio-tests-using-msbuild/","section":"Articles","summary":"When using a Continuous Integration server such as TeamCity, you’ll need to be able to perform the ability to run tests, the easiest and most controlled way is by writing your own MSBuild Script.\nHere is a little build script that finds all the test files and then runs them using Gallio, of course you need to reference the Gallio MSBuildTasks, in my case they are in C:\\Program Files\\Gallio\\bin\\Gallio.MsBuildTasks.dll\n","title":"Running Gallio tests using MSBuild","type":"articles"},{"content":"I’ve been using Home Server to take backups of all my machines on my network, and I am very pleased, it’s an install and forget service, which is nice for a change from Microsoft. Until I had to upgrade my server and install two new hard drives. I found my old backups were no longer available, this would not have been an issue until you need some information held on an old backup, which my Son did. So after many hours of trying I finally found a document that explains the complete process\nWindows_Home_Server_Technical_Brief_-_Home_Computer_Backup_and_Restore.docx (999.09 kb)\nContents\nHome Computer Backup Overview……………………………………………………………………….. 4\nFeatures and Functionality……………………………………………………………………………….. 4\nBenefits……………………………………………………………………………………………………. 5\nBackup and Restore In Depth………………………………………………………………………………. 6\nWindows Home Server Console………………………………………………………………………… 6\nHow Backup Is Implemented………………………………………………………………………………. 9\nHow Backups Are Stored………………………………………………………………………………. 12\nRestoring Individual Files and Folders…………………………………………………………………. 14\nRestoring a Home Computer…………………………………………………………………………… 16\nBackup Settings and Backup Cleanup………………………………………………………………… 19\nAdditional Tips…………………………………………………………………………………………… 22\nBackup service is not running……………………………………………………………………….. 22\nSaving a Copy of the Backup Database……………………………………………………………. 23\nDeleting the Backup Database………………………………………………………………………. 24\nRestoring a Backup Database………………………………………………………………………. 25\nMore Information…………………………………………………………………………………………… 26\nHome Computer Backup Overview Windows® Home Server will automatically backup your home computers to the home server and allow you to easily restore the entire computer or an individual file or folder to a previous point in time. The Windows Home Server Backup solution backs up only the data that has not already been backed up. Even if you have several copies of the same data on different computers, the data is backed up only once on your home server and your home server keeps track of what data was stored on each home computer on each day. This makes it efficient in the time it takes for backups to complete and the amount of space that is used on your home server. Features and Functionality The core features of Windows Home Server Home Computer Backup and Restore are:\n· Performs Automated Daily Backup of your Home Computers\nComputer backups are automatically configured when you install the Windows Home Server Connector software on your home computers. Backup is performed on a daily basis for every configured computer. You can connect 10 computers at one time to Windows Home Server. · Restores an Entire Home Computer\nIf you want to restore your computer to a previous point in time, you restart the home computer from the Home Computer Restore CD. The computer connects to your home server and provides a wizard to follow for restoring a single hard drive or multiple hard drives from the backup of that computer that is stored on your home server. · Restores Individual Files and Folders You can also restore individual files or folders by selecting a specific backup of a home computer from the Windows Home Server Console application. Windows Explorer displays a window with the files and folders that were backed up for that computer on that day. You can drag individual files or entire folders from this window to your Windows Desktop or another location on your home computer.\nBenefits Windows Home Server Home Computer Backup is unique compared to other solutions. Some of the benefits are: · Peace of Mind\nImagine the peace of mind that comes from automatic daily backups. Windows Home Server helps keep your family’s important files safe, backing up every computer in your home, every day.\n· Simple to Restore an Entire Computer\nYou can restore a home computer to a previous point in time by using the Home Computer Restore CD and answering a few questions.\n· Saves Disk Space on Your Home Server\nWhen your home server has a copy of a given piece of data, it keeps track of which home computer had that data on which day. The data is only stored once on the home server.\n· Saves Time\nWhen your home server has a copy of a given piece of data, it does not have to be copied to the server again even if the data is on another home computer. After you initially back up your first personal computer, subsequent backups take less time to complete. In a home network, there are many duplicate files on your home computers, especially the files belonging to the operating systems and applications that are installed on every computer.\nBackup and Restore In Depth This section of the technical brief explains how Windows Home Server Home Computer Backup and Restore works.\nWindows Home Server Console The Windows Home Server Console provides you with the ability to see which home computers have been configured to be backed up and the backup status of each of your home computers. After you install Windows Home Server Connector on each of your home computers, they are automatically backed up each night to your home server. The options on the Computers \u0026amp; Backup tab allow you to:\n· View Backups Browse the existing backups of a home computer.\n· Backup Now Initiate a manual backup of a home computer. · Configure Backup Change the backup settings of a home computer.\n· Remove Computer Delete computer and backups from the home server. Figure 1: Windows Home Server Computers \u0026amp; Backup tab\nConfiguring Backups\nIf you add or remove hard drives from your home computers, you need to use the Configure Backup option from the Windows Home Server Console to inform your home server of the new hard-drive configuration on the home computer. You can also use the Configure Backup option to exclude certain folders from being backed up from a home computer to a home server. By default, Windows Home Server avoids backing up certain files and folders each day. This list includes:\n· User temporary files\n· System page file\n· Hibernation file\n· Client-side cache folders\n· Shadow volume implementation folders\n· Media Center temporary files\nCaution To save space in the backup database on your home server, recorded TV shows on Windows Media Center are not backed up from a home computer to your home server. If you want to have a backup copy of your recorded TV shows, one option is to copy the Recorded TV folder from your computer running Windows Media Center to a shared folder on your home server.\nYou can temporarily turn off backups for one or more of your home computers. You may want to do this for a computer that will be out of your home for a week or more or for a home computer that you no longer use but you want to keep a backup image. To turn on or turn off backups\nOpen the Windows Home Server Console. Click the Computers \u0026amp; Backup tab. Right-click a computer, and then select Turn Off Backups or Turn On Backups Daily automatic backups do not occur on a computer if you turn off backups. However, you can manually back up the computer if you right-click it in the Windows Home Server Console, and then click Backup Now.\nRemoving Computers\nIf you no longer want to save the backups for a home computer, you can remove that computer from the Windows Home Server Console, by using the Remove Computer option. If possible, uninstall the Windows Home Server Connector software from the computer before you remove the computer from the console. If your computer is still on you will be required to do this. If you cannot remove the Windows Home Server Connector software because the computer is no longer available, you can still safely remove the computer from the console.\nTo remove a computer from the console\nOpen the Windows Home Server Console. Click the Computers \u0026amp; Backup tab. Right-click a computer, and then click Remove. Caution All existing backups for a home computer are deleted from the home server if you remove the home computer from the console.\nHow Backup Is Implemented When you install the Windows Home Server Connector software on your home computers, they are configured to automatically back up every day during the backup time that you choose. Your computers must be turned on or they must be in sleep or hibernate mode to be automatically backed up. If a computer is in sleep or hibernate mode, it wakes up, runs Backup, and then goes back in to sleep or hibernate mode.\nImportant Laptops and other battery-powered computers must be plugged in to AC power to be automatically backed up. Although the home computer on battery power will be awakened, Windows Home Server will recognize it as battery-powered and automatic backup will not initiate. On home computers running Windows XP, there is no easy way to tell whether the computer was awakened from sleep or hibernate, so the computer is put back to sleep when the backup process completes. You can also disable this functionality by un-checking the “Wake This Computer For Backup” item by right clicking the Windows Home Server Connector in the system tray.\nYou should back up all of the hard drives on each home computer including the system volume (typically, drive C:). If the hard drive that contains the system volume fails, you can restore it by using the Home Computer Restore CD and restarting the computer. You should also back up any volume that contains valuable or important files that you do not want to lose. For example, you may have irreplaceable pictures or videos, which you can back up to protect them from a hard drive failure.\nImportant Windows Home Server backs up only the NTFS file system volumes. If the volume on a home computer was created as a FAT or FAT32 volume, it is not displayed in the list of volumes to back up. Changing the existing file system on a hard disk volume from FAT or FAT32 to NTFS can be time consuming, but after the system is converted to NTFS, Windows Home Server can back it up. If you decide to upgrade your file system to NTFS, you should back up your data by copying it to an external hard drive and then reformat the volume using NTFS.\nNote\nYou can use the Convert.Exe program to change a hard disk volume from FAT or FAT32 to an NTFS volume without formatting the volume. If you use the Convert.Exe program, your NTFS file system will be formatted with 512 byte clusters, thereby reducing the efficiency of the Windows Home Server backup database.\nThe home computer backup solution in Windows Home Server has a single-instance store at the cluster level. Clusters are typically collections of data stored on the hard drive, 4 kilobytes (KB) in size. Every backup is a full backup, but the home server only stores each unique cluster once. This creates the restore-time convenience of full backups (you do not have to repeat history) with the backup time performance of incremental backups. The home computer backup occurs as follows:\n· When a home computer is backed up to the home server, Windows Home Server software figures out what clusters have changed since the last backup. · The home computer software then calculates a hash for each of these clusters and sends the hashes to the home server. A hash is a number that uniquely identifies a cluster based on its contents.\n· The home server looks into its database of clusters to see if they are already stored on the home server. · If they are not stored on the home server already, then the home server asks the home computer to send them.\n· All file system information is preserved such that a hard disk volume (from any home computer) at any backup point (time) can be reconstituted from the database.\nFigure 2: Windows Home Server backup solution stores unique data once\nThe copies of the clusters that are stored on the home server in the order they are received. Additionally, the home server stores metadata files which allow it to deduce which clusters belong to which home computer at which times. The metadata that is typically stored for each home computer usually takes less than 5 percent of the space of the clusters that are backed up.\nSome of the implications of this backup approach are:\n· The first backup always needs to send the entire contents of the disk to the home server.\n· The first backup of a different home computer needs to read all of its data but only transmit the content of those clusters that the home server does not already have from another home computer.\n· Subsequent backups after little change typically only read a small amount of data on the home computer and send the new clusters to the home server.\n· After you defragment a home computer, the next backup may need to read a large amount of data from the disk (many files will appear to have been changed), but it only sends a relatively small amount of data to the home server because the clusters have been reorganized, but they have not changed.\nNote\nThe first backup should be of the home computer with the largest hard drive that is connected through a wired Ethernet connection, because the first backup of a home computer to your home server sends the entire contents of the disk to the home server over your home network.\nHow Backups Are Stored The home server side of the solution is a database that is specifically designed to efficiently backup multiple home computers on a daily basis. The cluster data and metadata from each home computer is stored on the home server hard drives. The backup database is stored entirely in the folder D:\\folders\\{00008086-058D-4C89-AB57-A7F909A47AB4}\\. The content of this folder is migrated by Windows Home Server Drive Extender from the primary data partition to a secondary data partition if the home server has more than one hard drive. The Windows Home Server backup engine stores data at the cluster level. Clusters are typically 4 kilobytes (KB) in size. The backup database records include clusters and hashes of these clusters (a hash is a number that uniquely identifies a cluster based on its contents). The database also contains information on the structure of a hard disk volume (NTFS information).\nDuring the backup process, a cluster from one home computer that is identical to a cluster from a different home computer is sent to the server exactly once and stored exactly once. Because Windows Home Server backs up multiple computers (space) every day (time) to a single database, it in essence supports “single instancing of home computer backups across space and time.” When the cluster size is different among volumes, no data is shared between the volumes in the backup database. By default, every newly created NTFS volume gets a cluster size of 4 KB. A few volumes that started out as FAT and were converted to NTFS have a cluster size of 512 KB. The only way to get any other cluster size is to format the volume yourself and explicitly request a different size.\nNote\nYou can maximize the efficiency of the home server backup database by ensuring that all of the hard drives on your home computers are formatted with NTFS and with a cluster size of 4 KB.\nThe backup database is a collection of files that can be broken into three categories:\n· Global files – Files that track the history of all home computer backups and all of the other files in the backup database.\n· Cluster files – Files that store the actual cluster data from the home computers. These are usually in 4096 byte increments. These files grow to 4 GB in size before a new file is created. These files are stored as Data.XXXX.Z.dat, where XXXX=cluster size in bytes, and Z=0,1,2,…\n· Home Computer specific files – A boot record and data for each hard drive volume that gets backed up from each home computer.\nRestoring Individual Files and Folders To restore individual items from a previous backup stored on the home server, a virtual volume driver is loaded on the home computer. This allows a previous image of a hard drive to be mounted, as if it were a read-only volume, across the home network. This driver opens a connection to the home server, and it receives the relevant clusters from the home server to build a virtual view into what a given hard drive looked like on a given day. The read-only volume is displayed in Windows Explorer where a user can drag the files and folders that they want to restore to the Windows Desktop of the home computer they are using.\nImportant A home computer that is behind your home firewall and has the Windows Home Server Connector software installed can create a backup without further authorization or authentication. However, restoring individual files and folders and restoring home computers using the Home Computer Restore CD requires the Windows Home Server password.\nTo browse and restore individual files and folders from a backup\n1. Open the Windows Home Server Console.\n2. Click the Computers \u0026amp; Backup tab.\n3. Select a home computer, and then click View Backups.\n4. Select a backup, and then click Open.\n5. Select a volume to open, and then click Open.\nImportant The Opening Backup status window appears while the backup opens. If you are prompted to restart your computer after the virtual volume driver is installed, ignore this message; you do not need to restart your computer.\nFigure 3: Status window to ignore when you restore files and folders\nTo restore files and folders\nWhen the backup library window opens, drag the backup files and folders that you want to restore to a folder on your home computer. Close the window when you are done copying the files and folders that you want to restore. Figure 4: Home computer backup for a specific date\nRestoring a Home Computer After backups for a home computer are stored on the home server, you can use the Home Computer Restore CD to restore the entire content of one or more home computer hard drives to a previous point in time. Figure 5: Windows Home Server Restore Computer Wizard\nThe system volume of a home computer contains the hardware-specific files that you need to start your Microsoft® Windows operating system. This is usually the C: drive. If this volume is damaged, you will not be able to start your home computer, and you need to start your computer from your Home Computer Restore CD.\nTo restore a hard drive volume of a home computer\nPlace the Home Computer Restore CD in the optical drive of the home computer for which you want to restore one or more hard drive volumes. Restart the computer, and boot from the CD. Follow the instructions in the Restore Computer Wizard to restore the hard drives on your home computer. Important Your home computer must be connected to the home network with an Ethernet network cable before you begin the restore. In most cases, you cannot use a wireless connection, and attempting to use a wireless connection is an unsupported scenario.\nEvery time Windows Home Server backs up a home computer, it saves the drivers for the home computer in the backup that is stored on the home server. When you use the Home Computer Restore CD, you will be prompted if your home computer requires drivers that are not available on the Home Computer Restore CD. If you need to access the drivers for any of your home computers (for example, during a computer restore), you can open a backup for that home computer and copy the drivers to a USB flash drive. To copy drivers for a home computer from a backup stored on the home server\nOpen the Windows Home Server Console. On the Computers \u0026amp; Backup tab, click the computer that you need drivers for. Click View Backups. Select the most recent backup, and then click Open. Select a volume to open (any volume will work), and then click Open. A window opens showing the files and folders in the backup. Plug in your USB flash drive. Copy the Windows Home Server Drivers for Restore folder from the open window to your USB flash drive. Remove the flash drive, and then insert it into the home computer that is being restored. Figure 6: Home computer drivers to use for Home Computer Restore\nYou can use the USB flash drive to install drivers for your home computer’s specific hardware when you restore the home computer. The Home Computer Restore CD looks for additional drivers on a USB flash drive as part of the initial boot process. The drivers you are most likely to need during a home computer restore are the network driver and the storage-device driver.\nImportant If you are restoring from a 64-bit computer the drivers that are stored in the backup will be 64-bit. These will not function with the 32-bit restore CD. Therefore it is may be necessary to obtain 32-bit versions of the network driver and storage-device drivers for your 64-bit computer, while doing a restore of your home computer.\nBackup Settings and Backup Cleanup There are a few settings that you can configure for Windows Home Server Backup from the Windows Home Server Console. The Backup Time defines what hours during each day that backup processes will run, and the Automatic Backup Management settings define a retention policy for the home computer backups.\nFigure 7: Backup settings\nIf you have multiple home computers, they back up sequentially. Therefore, backups can potentially happen during the entire backup window. If a backup is still in progress when the backup time ends, it finishes but no new backups can start. Any computer that has not yet started its backup tries again during the next backup time. The Backup Time setting is limited so that your computers are not busy backing up when you want to use them. Note\nIn general, the Backup Time should be set for a time when people in your household will not be using the home computers. The longer the time period, the more likely it is that all of your home computers will be backed up each day.\nHome computers initiate the backup process as a hidden scheduled task. The home computers randomly select a time each day during the Backup Time to initiate their daily backup to the home server, and they alternate which computer will back up first on a given day. Only one home computer can back up at a time, so if another computer tries to start a backup to the home server, it will wait until the first computer’s backup completes.\nDaily backups of all your home computers accumulate on your home server over time. To help you manage these backups, Windows Home Server provides Automatic Backup Management. With Automatic Backup Management, you can configure how many backups to keep for each of your home computers. To configure how many backups to keep, set the number of months to keep the first backup of the month, the number of weeks to keep the first backup of the week, and the number of days to keep the first backup of the day.\nIf you click View Backups from the Windows Home Server Console, you can see the three options for each home computer backup:\n· Manage automatically (processed as part of Backup Cleanup)\n· Keep the backup (kept until users decides to change this option)\n· Delete at next Backup Cleanup\nFigure 8: Available backups for NEW-LAPTOP home computer Important Home computer backups that are manually initiated by using the Backup Now option are marked with the Keep this backup option, until someone explicitly changes them from the Windows Home Server Console.\nBackup Cleanup runs once a week at the beginning of the Backup Time on Sunday. It has two purposes: Delete the metadata about home computer backups that are no longer needed Delete copies of clusters that are no longer referenced by any home computer backup. Deleting the metadata is relatively fast (typically a few minutes per home computer), but it does not recover much space because the metadata for each home computer backup is usually less than five percent of all of the space consumed by the backup database. Deleting copies of clusters rarely recovers much space because the backup database is a single instance store of the unique clusters stored on your home computers. If another home computer backup that references a given cluster still exists, then the cluster will continue to be stored in the backup database.\nImportant If you temporarily stop the backup of a home computer, Windows Home Server continues to apply the Automatic Backup Management settings for your home computer backups. For example, assume your Automatic Backup Management settings are set for 3 days, 3 weeks, and 3 months. If you stop backing up a home computer, your home server will continue to keep the last three daily backups, weekly backups, and monthly backups, if they exist.\nIf you remove a computer from the Windows Home Server Console, all of the backups for that home computer will be deleted during the next Backup Cleanup. This is when you will see the largest decrease in the size of the backup database, especially if the home computer had a lot of unique data.\nNote\nWindows Home Server checks for Windows Updates at the beginning of the Backup Time. Depending on the requirements of the updates, your Windows Home Server may restart during this time.\nAdditional Tips Following are a few additional tips and techniques for situations that you may encounter or you may want to experiment with in Windows Home Server Backup and Restore.\nBackup service is not running You may see the following error: “If backup service is not running, please restart the console.” If you see this error, try resetting the console before connecting to Windows Home Server.\nTo reset the Windows Home Server Console\n1. Right-click the Windows Home Server icon in the taskbar, and then click Windows Home Server Console.\n2. On the console Password page, click Options.\n3. Click Reset the Windows Home Server Console.\n4. Click OK.\nCaution Ensure that Backup Cleanup is not running and that none of the home computers are being backed up during the following tasks: Saving a Copy, Deleting, and Restoring the Backup Database. Saving a Copy of the Backup Database The Windows Home Server backup database is not duplicated by Windows Home Server Drive Extender. So if you lose a single hard drive on your home server, you could possibly lose all of the backups of your home computers. You may want to periodically copy the entire backup database from your home server to an external hard disk that you attach to your home server. The external hard disk should not be added to the Server Storage on your Windows Home Server. Important The cluster data files stored in backup database can grow to 4 GB, so it is important that the external hard disk is formatted as NTFS to support copying these large files. Some file systems, such as FAT-32 allow a maximum file size of 2 GB.\nThe backup database is stored entirely in the folder D:\\folders\\{00008086-058D-4C89-AB57-A7F909A47AB4}.\nTo copy the backup database from your Windows Home Server\n(In this example, assume that the external hard drive is given a drive letter of E:)\n1. Run mstsc.exe to start a Remote Desktop Connection session to your home server.\nCaution Be careful when using a Remote Desktop Connection to your home server. You can damage Windows Home Server functionality if you use it incorrectly. 2. Plug in an external hard drive to your home server (do not add it to the Server Storage through the Windows Home Server Console). 3. Open a Command Prompt, Click Start, Run and type CMD\n4. Type net stop PDL.\n5. Type net stop WHSBackup to stop the Windows Home Server Backup service.\n6. Copy the contents of D:\\folders\\{00008086-058D-4C89-AB57-A7F909A47AB4} to the external hard drive E:. 7. Type net start WHSBackup to restart the Windows Home Server Backup service.\n8. Type net start PDL.\nThe only relevant settings that Windows Home Server backup stores in the registry on the home server are Backup Time and Automatic Backup Management. Deleting the Backup Database You may want to delete the entire backup database from your home server to reclaim the disk space. The backup database is stored entirely in the folder D:\\folders\\{00008086-058D-4C89-AB57-A7F909A47AB4}.\nTo delete the backup database on your Windows Home Server\n1. Run mstsc.exe to start a Remote Desktop Connection session to your home server.\n2. Open a Command Prompt, Click Start, Run and type CMD\n3. Type net stop PDL.\n4. Type net stop WHSBackup to stop the Windows Home Server Backup service.\n5. Delete the contents of D:\\folders\\{00008086-058D-4C89-AB57-A7F909A47AB4}. Do not delete the folder.\n6. Type net start WHSBackup to restart the Windows Home Server Backup service.\n7. Type net start PDL.\nImportant After deleting the backup database, you need to reinstall the Windows Home Server Connector software or run the Discovery.Exe program on each of your home computers to re-establish a relationship between your home computers and your home server so new backups will occur. Restoring a Backup Database You may want to restore an entire backup database, which you previously saved on an external hard drive, to your home server. Prior to restoring a backup database, you need to delete the existing backup database from the home server. Currently, there is not an option to merge backup databases into a single database. To restore the backup database to your Windows Home Server\n(In this example, assume that the external hard drive is given a drive letter of E:, and it has a copy of a home server backup database that was previously saved as described in the Saving a Copy of the Backup Database section earlier in this document.)\n1. Run mstsc.exe to start a Remote Desktop Connection session to your home server.\n2. Plug in an external hard drive to your home server (do not add it to the Server Storage through the Windows Home Server Console). 3. Open a Command Prompt, Click Start, Run and type CMD.\n4. Type net stop PDL. 5. Type net stop WHSBackup to stop the Windows Home Server Backup service.\n6. Delete the contents of D:\\folders\\{00008086-058D-4C89-AB57-A7F909A47AB4}. Do not delete the folder.\n7. Copy the contents from the external hard drive E:\\folders\\{00008086-058D-4C89-AB57-A7F909A47AB4} to D:\\folders\\{00008086-058D-4C89-AB57-A7F909A47AB4}.\n8. Type net start WHSBackup to restart the Windows Home Server Backup service.\n9. Type net start PDL.\nMore Information For more information about Windows Home Server, see the Microsoft Web site (http://go.microsoft.com/fwlink/?LinkId=100260).\nFor more information about Windows Home Server Home Computer Backup and Restore, see the Community Forums at the Microsoft Web site (http://go.microsoft.com/fwlink/?LinkId=100263).\n","date":"5 June 2010","externalUrl":null,"permalink":"/how-does-home-server-take-those-backups/","section":"Articles","summary":"I’ve been using Home Server to take backups of all my machines on my network, and I am very pleased, it’s an install and forget service, which is nice for a change from Microsoft. Until I had to upgrade my server and install two new hard drives. I found my old backups were no longer available, this would not have been an issue until you need some information held on an old backup, which my Son did. So after many hours of trying I finally found a document that explains the complete process\n","title":"How does Home Server take those backups?","type":"articles"},{"content":"The nice thing about MEF is the ability to dynamically load additional modules in to an application with very little effort.\nTo make it even easier, I’ve generated a small MEF Compose which will load up all DLL in a directory automatically.\nprivate void Compose()\n{\nvar catalog = new AggregateCatalog(\nnew AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()),\nnew DirectoryCatalog(@”.\\Extensions”));\nvar container = new CompositionContainer(catalog);\ncontainer.ComposeParts(this);\n}\nThe above code works well for .NET, however for some reason .NET 3.5 version, which is available from CodePlex just comes back with nulls, so here is a solution for MEF for .NET 3.5\nprivate void Compose()\n{\nvar key = Assembly.GetExecutingAssembly().GetName().GetPublicKey();\nvar catalog = new AggregateCatalog();\ncatalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));\nvar dir = new DirectoryInfo(@”.\\Extensions”);\nAssembly assembly;\nforeach (var file in dir.GetFiles(“*.dll”))\n{\nassembly = Assembly.LoadFile(file.FullName);\nbyte[] assemblykey = assembly.GetName().GetPublicKey();\ncatalog.Catalogs.Add(new AssemblyCatalog(assembly));\n}\nvar container = new CompositionContainer(catalog);\ncontainer.ComposeParts(this);\n}\n","date":"4 June 2010","externalUrl":null,"permalink":"/how-to-get-mef-to-load-all-assemblies-in-a-directory/","section":"Articles","summary":"The nice thing about MEF is the ability to dynamically load additional modules in to an application with very little effort.\n","title":"How to get MEF to load all Assemblies in a directory","type":"articles"},{"content":"MEF has now been released, a Plug-In Framework, for .Net 4.0\nAfter reading up on CodePlex, I have generated a small application that provides a plug-in framework, see attached below.\nhttp://mef.codeplex.com/wikipage?title=Guide\u0026amp;referringTitle=Overview\nMEF.zip (70.88 kb)\nI’ve also produced a .NET 3.5 version too:\nMEF in 3.5.zip (427.41 kb)\nFew MEF links:\nGlenn Block\nNicholas Blumhardt\nMEF on CodePlex\nChannel 9 Silverlight 4 MEF Screencasts\nMEF 101\n","date":"27 May 2010","externalUrl":null,"permalink":"/using-mef-to-provide-plugins/","section":"Articles","summary":"MEF has now been released, a Plug-In Framework, for .Net 4.0\nAfter reading up on CodePlex, I have generated a small application that provides a plug-in framework, see attached below.\nhttp://mef.codeplex.com/wikipage?title=Guide\u0026referringTitle=Overview\nMEF.zip (70.88 kb)\nI’ve also produced a .NET 3.5 version too:\n","title":"Using MEF to provide PlugIns","type":"articles"},{"content":"The use of DataAnnotations, has increased over the years, as many frameworks are using it more and more, (MVC, Silverlight, etc).\nHowever if you need to perform validation within your application and it is not any known framework then can we still use DataAnnotations?\nThe answer is yes, I’ll try and take you through how you can go about it.\nFirst lets create a class that we are going to use:\npublic class Contact\n{\n[Required]\n[RegularExpression(@”\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*([,;]\\s*\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*)*”, ErrorMessage = “Invalid email address”)]\npublic string Email { get; set; }\n[Required]\n[StringLength(20)]\npublic string FirstName { get; set; }\n[Required]\npublic string LastName { get; set; }\n[Range(10,30)]\npublic int Age {get;set;}\npublic string City { get; set; } }\nAll of these validations are standard and out of the box when using DataAnnotations.\nNext we need to be able to hold the Error Information, so I’ve created a class called ErrorInfo\npublic class ErrorInfo\n{\npublic ErrorInfo(string propertyName, string errorMessage, object instance)\n{\nPropertyName = propertyName;\nErrorMessage = errorMessage;\nInstance = instance;\n}\npublic string PropertyName { get; set; }\npublic string ErrorMessage { get; set; }\npublic object Instance { get; set; }\n}\nNow the clever bit, the Validation Runner (this was kindly supplied by Steve Sanderson and his xVal)\ninternal static class DataAnnotationsValidationRunner\n{\npublic static IEnumerable\u0026lt;ErrorInfo\u0026gt; GetErrors(object instance)\n{\nreturn from prop in TypeDescriptor.GetProperties(instance).Cast\u0026lt;PropertyDescriptor\u0026gt;()\nfrom attribute in prop.Attributes.OfType\u0026lt;ValidationAttribute\u0026gt;()\nwhere !attribute.IsValid(prop.GetValue(instance))\nselect new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance);\n}\n}\nSo that is the hard work done, now lets check for validation:\nIEnumerable\u0026lt;ErrorInfo\u0026gt; errors = DataAnnotationsValidationRunner.GetErrors(contact);\nHow easy is that?\nOkay now lets pick things up, What I would like to do next is Validate the City, to be a city in the UK, something like this would be nice:\n[City(ValidCity=”Gloucester”)]\npublic string City { get; set; }\nIn order to do this you are going to have to generate your own Attribute which needs to be based on the ValidationAttribute, again this is quite simple\npublic class CityAttribute : ValidationAttribute\n{\npublic string ValidCity { get; set; }\npublic override bool IsValid(object value)\n{\nif (value == null)\n{\nreturn true;\n}\nif (value.ToString() != ValidCity)\n{\nreturn false;\n}\nreturn true;\n}\n}\nSo you now can generate your own custom validation attributes with your own business rules.\nDataAnnotationsValidation.zip (11.78 kb)\n","date":"26 May 2010","externalUrl":null,"permalink":"/how-to-use-dataannotations-validation/","section":"Articles","summary":"The use of DataAnnotations, has increased over the years, as many frameworks are using it more and more, (MVC, Silverlight, etc).\nHowever if you need to perform validation within your application and it is not any known framework then can we still use DataAnnotations?\n","title":"How to use DataAnnotations Validation","type":"articles"},{"content":" What is code coverage?\nCode coverage, in short, is all about how thoroughly your tests exercise your code base. The intent of tests, of course, is to verify that your code does what it’s expected to, but also to document what the code is expected to do. Taken further, code coverage can be considered as an indirect measure of quality — indirect because we’re talking about the degree to what our tests cover our code, or simply, the quality of tests. In other words, code coverage is not about verifying the end product’s quality.\nSo, how does code coverage differ from other types of testing techniques? Code coverage can be classified as white-box testing or structural testing because the “assertions” are made against the internals of our classes, not against the system’s interfaces or contracts. Specifically, code coverage helps to identify paths in your program that are not getting tested. It is because of this distinction that code coverage shows its usefulness when testing logic-intensive applications with a lot of decision points.\nNeeds for Code Coverage\nTo be able to use a code coverage tool we need a number of requirements, they are: Command line driven Xml reports Usable within any unit testing framework Support for up to .Net 4.0 framework Stable and supported Tools\nThere are a number of tools available for code coverage, mainly in the Java world however here are a few in the .NET world PartCover http://partcover.blogspot.com/\nNCover http://www.ncover.com/\nTestDriver.NET http://www.testdriven.net/Default/?ReferrerId=7393\ndotCover http://confluence.jetbrains.net/display/DCVR/dotCover+Early+Access+Program\nQuestion is which tool and why?\nThe quickest answer would be dotCover as it is from JetBrains, however dotCover is currently only in Early Access Program, and perhaps in the future this would fill our needs. PartCover, does not appear to be well supported and a little tricky to get working. TestDriver.NET is perfect for checking out your code coverage from within Visual Studio and works well with Gallio too, however is not well supported and the documentation is very sparse. Which leaves us with NCover, although it used to be free, the owners have now produced a commercial version, which is very well supported, supporting all .NET languages, 32 and 64 bit support, no special builds required, Sequence point coverage reporting and Branch coverage reporting, XML coverage data output for integration to CI servers, any many more. It would be nice for each developer to have NCover, however the cost is quite high ($199.00 per user), and if budgets are restricted then a single version would be sufficient for the CI server. Summary\nI have not gone in to great detail about how to perform code coverage, as there is ample information on the internet, what I have tried to do is provide a simple justification to why code coverage is an integral part of the development process.\nMy recommendation would be NCover, mainly because it appear to be the only fully supported Code Coverage tool for .NET Another Code Coverage tool, which is built in to Visual Studio Team edition, I have not covered here, as it was not available for me at the time of writing. Thanks Nathan Gloyn for point this out.\n","date":"19 May 2010","externalUrl":null,"permalink":"/code-coverage/","section":"Articles","summary":" What is code coverage?\nCode coverage, in short, is all about how thoroughly your tests exercise your code base. The intent of tests, of course, is to verify that your code does what it’s expected to, but also to document what the code is expected to do. Taken further, code coverage can be considered as an indirect measure of quality — indirect because we’re talking about the degree to what our tests cover our code, or simply, the quality of tests. In other words, code coverage is not about verifying the end product’s quality.\n","title":"Code Coverage","type":"articles"},{"content":"From time to time I need to generate Sequence Diagrams, as this are required to graphically represent processes, as a consultant each customer has a different sent of tools you can and can not use. So it becomes hard to generate what should be something you don’t have to think about.\nI found a great on-line tool Web Sequence Diagrams, it so simple and it also has a very easy to use API.\nJust to show you how easy here is what I generated in what must have been 5 minutes\nIt can also be support in plain HTML, as you can see in the attached file\nCommit Sequence.htm (457.00 bytes)\n","date":"14 May 2010","externalUrl":null,"permalink":"/generating-sequence-diagrams/","section":"Articles","summary":"From time to time I need to generate Sequence Diagrams, as this are required to graphically represent processes, as a consultant each customer has a different sent of tools you can and can not use. So it becomes hard to generate what should be something you don’t have to think about.\n","title":"Generating Sequence Diagrams","type":"articles"},{"content":"When handling XML files you are going to need to validate the XML, and the best way, currently, is to use an XSD Schema. It took me a little while to work out how to do this, and with help from Assaf Lavie I finally came up with a method to validate two streams, one holding the XML the other the XSD.\npublic void Validate(Stream xml, Stream xsd)\n{\nif (xml == null)\n{\nthrow new ArgumentNullException(“xml”);\n}\nif (xsd == null)\n{\nthrow new ArgumentNullException(“xsd”);\n}\nxml.Seek(0, SeekOrigin.Begin);\nvar readerXML = new StreamReader(xml);\nstring textXML = readerXML.ReadToEnd();\nif (string.IsNullOrEmpty(textXML))\n{\nthrow new ArgumentNullException(“xml need to hold some information”);\n}\nxsd.Seek(0, SeekOrigin.Begin);\nvar readerXSD = new StreamReader(xsd);\nstring textXSD = readerXSD.ReadToEnd();\nif (string.IsNullOrEmpty(textXSD))\n{\nthrow new ArgumentNullException(“xsd need to hold some information”);\n}\ntry\n{\n// 1- Set the streams to the beginning\nxml.Seek(0, SeekOrigin.Begin);\nxsd.Seek(0, SeekOrigin.Begin);\nvar errorMessages = new List\u0026lt;string\u0026gt;();\n// 2- Read XML file content var xmlReader = new XmlTextReader(xml);\n// 3- Read Schema file content StreamReader schemaReader = new StreamReader(xsd);\n// 4- Set Schema object by calling XmlSchema.Read() method XmlSchema Schema = XmlSchema.Read(schemaReader, (o, e) =\u0026gt;\n{\nerrorMessages.Add(e.Message);\n});\n// 5- Create a new instance of XmlReaderSettings object XmlReaderSettings readerSettings = new XmlReaderSettings();\n// 6- Set ValidationType for XmlReaderSettings object readerSettings.ValidationType = ValidationType.Schema;\n// 7- Add Schema to XmlReaderSettings Schemas collection readerSettings.Schemas.Add(Schema);\n// 8- Add your ValidationEventHandler address to // XmlReaderSettings ValidationEventHandler readerSettings.ValidationEventHandler += (o, e) =\u0026gt;\n{\nerrorMessages.Add(e.Message);\n};\n// 9- Create a new instance of XmlReader object XmlReader objXmlReader = XmlReader.Create(xmlReader, readerSettings);\n// 10- Read XML content in a loop while (objXmlReader.Read())\n{ /*Empty loop*/}\n// 11- Raise exception, if XML validation fails\nif (errorMessages.Count() \u0026gt; 0)\n{\nthrow new Exception(string.Join(“\\r\\n”, errorMessages.ToArray()));\n}\n}\ncatch (XmlException XmlExp)\n{\nthrow new XMLValidationException(XmlExp.Message, XmlExp);\n}\ncatch (XmlSchemaException XmlSchExp)\n{\nthrow new XMLValidationException(XmlSchExp.Message, XmlSchExp);\n}\ncatch (Exception GenExp)\n{\nthrow;\n}\nfinally\n{\nxml.Seek(0, SeekOrigin.Begin);\nxsd.Seek(0, SeekOrigin.Begin);\n}\n}\n","date":"6 May 2010","externalUrl":null,"permalink":"/validating-xml-against-an-xsd-schema/","section":"Articles","summary":"When handling XML files you are going to need to validate the XML, and the best way, currently, is to use an XSD Schema. It took me a little while to work out how to do this, and with help from Assaf Lavie I finally came up with a method to validate two streams, one holding the XML the other the XSD.\n","title":"Validating XML against an XSD Schema","type":"articles"},{"content":"The time has come where I needed to handle streams, so the first I needed to generate some tests and within these tests I need to generate a stream based on some text. So the first task was to convert a String in to a Stream, and while I am at it how about the other direction to (Stream to a String)\nString in to a Stream string text = “To Jani, Reminder Don’t forget me this weekend!'”;\nbyte[] byteArray = Encoding.ASCII.GetBytes(text);\nMemoryStream streamXML = new MemoryStream(byteArray);\nStream to a String xml.Seek(0, SeekOrigin.Begin);\nvar readerXML = new StreamReader(xml);\nstring textXML = readerXML.ReadToEnd();\n","date":"6 May 2010","externalUrl":null,"permalink":"/string-to-a-stream/","section":"Articles","summary":"The time has come where I needed to handle streams, so the first I needed to generate some tests and within these tests I need to generate a stream based on some text. So the first task was to convert a String in to a Stream, and while I am at it how about the other direction to (Stream to a String)\n","title":"String to a Stream","type":"articles"},{"content":"I came across a very easy to use and useful generation tool for objects today, NBuilder.\nThrough a fluent, extensible interface, NBuilder allows you to rapidly create test data, automatically assigning values to properties and public fields that are of type of the built in .NET data types (e.g. ints and strings). NBuilder allows you to override for properties you are interested in using lambda expressions.\nIf you understand Lambda then you’re going to be able to build test data for your objects.\nAll you need to do is reference FizzWare.NBuilder.dll in to your test project and you are off.\nFizzWare.NBuilder-2.1.9-beta.zip (32.47 kb)\n","date":"4 May 2010","externalUrl":null,"permalink":"/rapid-generation-of-test-objects/","section":"Articles","summary":"I came across a very easy to use and useful generation tool for objects today, NBuilder.\nThrough a fluent, extensible interface, NBuilder allows you to rapidly create test data, automatically assigning values to properties and public fields that are of type of the built in .NET data types (e.g. ints and strings). NBuilder allows you to override for properties you are interested in using lambda expressions.\n","title":"Rapid Generation of test objects","type":"articles"},{"content":"If you have ever come across generating XSD’s then you will soon find out that it’s a new ball game. So in order to help you along I have generated this reference point of items that I have found useful.\nXML Schema data types. The most common types are:\nxs:string xs:decimal xs:integer xs:boolean xs:date xs:time Optional and Required Attributes Attributes are optional by default. To specify that the attribute is required, use the “use” attribute:\n\u0026lt;xs:attribute name=”lang” type=”xs:string” use=”required”/\u0026gt;\n","date":"29 April 2010","externalUrl":null,"permalink":"/xsd-schemas-reference/","section":"Articles","summary":"If you have ever come across generating XSD’s then you will soon find out that it’s a new ball game. So in order to help you along I have generated this reference point of items that I have found useful.\n","title":"XSD Schema’s – Reference","type":"articles"},{"content":"I came across a very simple to use XML to XSD generator today\nhttp://www.xmlforasp.net/CodeBank/System_Xml_Schema/BuildSchema/BuildXMLSchema/\n","date":"28 April 2010","externalUrl":null,"permalink":"/the-need-to-generate-an-xsd-from-xml/","section":"Articles","summary":"I came across a very simple to use XML to XSD generator today\nhttp://www.xmlforasp.net/CodeBank/System_Xml_Schema/BuildSchema/BuildXMLSchema/\n","title":"The need to generate an XSD from XML","type":"articles"},{"content":"While attending a DotNetDevNet meeting in September 2009, by Stephen Oakman and Ronnie Barker, I remembered they used a tool called AutoHotKey, I’ve just revisited the tool and found it has increased my productivity, and combining it with Jean-Paul S. Boodhoo article for replacing spaces with underscores it is just perfect for generating unit tests.\n","date":"27 April 2010","externalUrl":null,"permalink":"/autohotkey-to-increase-productivity/","section":"Articles","summary":"While attending a DotNetDevNet meeting in September 2009, by Stephen Oakman and Ronnie Barker, I remembered they used a tool called AutoHotKey, I’ve just revisited the tool and found it has increased my productivity, and combining it with Jean-Paul S. Boodhoo article for replacing spaces with underscores it is just perfect for generating unit tests.\n","title":"AutoHotKey to increase productivity","type":"articles"},{"content":"WCF is a very powerful tool for developers, and I’m sure as you dive in to the development environment you will come across the WCF Message, which is part of System.ServiceModel.Channels Namespace. You should be aware that a message body can only be accessed once and a message can only be written once. This will in turn can cause a problem if you are creating your own IDispatchMessageInspector, as at some you will need to read the message and once you have read it, you are buggered!\nSo in order to use the Message you will have to copy the message in to a buffer using the CreateBufferCopy method, here is how you go about it\npublic void Validate(ref Message message)\n{\nMessageBuffer buffer = message.CreateBufferedCopy(int.MaxValue);\ntry\n{\nValidateInput(buffer.CreateMessage());\n}\ncatch (Exception)\n{\nthrow;\n}\nmessage = buffer.CreateMessage();\n} ","date":"23 April 2010","externalUrl":null,"permalink":"/wcf-message-can-only-be-read-once/","section":"Articles","summary":"WCF is a very powerful tool for developers, and I’m sure as you dive in to the development environment you will come across the WCF Message, which is part of System.ServiceModel.Channels Namespace. You should be aware that a message body can only be accessed once and a message can only be written once. This will in turn can cause a problem if you are creating your own IDispatchMessageInspector, as at some you will need to read the message and once you have read it, you are buggered!\n","title":"WCF Message can only be read once","type":"articles"},{"content":"I’ve been dealing with REST services within WCF, and one thing that has come to my attention is that the calling service or third party only has access to the REST interface and the XSD’s.\nThe XSD’s holds all the contract information, therefore if you need to generate a concreteclass you are going to have to translate the XSD to an object. I’ve have come across the XSD Object Generator frm Microsoft which appears to do the job.\nXSDObjectGen.msi (667.00 kb)\n","date":"16 April 2010","externalUrl":null,"permalink":"/xsd-to-objects/","section":"Articles","summary":"I’ve been dealing with REST services within WCF, and one thing that has come to my attention is that the calling service or third party only has access to the REST interface and the XSD’s.\n","title":"XSD to Objects","type":"articles"},{"content":"After attending a talk on Silverlight 4, MVVM and TDD with Jesse Liberty, I thought it would be an idea to find out more information on MVVM, James Green provided me with a number of worth while links by Jason Dollinger from Lab49. The main blog post is here http://blog.lab49.com/archives/2650 but the actual video is here http://www.lab49.com/files/videos/Jason%20Dolinger%20MVVM.wmv big download (about 1.5 hours).\nThe source code for the project he is doing is here http://blog.lab49.com/archives/2689\nAnother good one is by Karl Shifflet (he’s a VS IDE developer) http://channel9.msdn.com/shows/Continuum/MVVM/\nThis guy is worth following as well http://sachabarber.net/?cat=17\nWant to know not only MVVM but all about Silverlight 4 too, check out Scott Gu’s post for Silverlight 4 Training Kit ","date":"13 April 2010","externalUrl":null,"permalink":"/mvvm-material/","section":"Articles","summary":"After attending a talk on Silverlight 4, MVVM and TDD with Jesse Liberty, I thought it would be an idea to find out more information on MVVM, James Green provided me with a number of worth while links by Jason Dollinger from Lab49. The main blog post is here http://blog.lab49.com/archives/2650 but the actual video is here http://www.lab49.com/files/videos/Jason%20Dolinger%20MVVM.wmv big download (about 1.5 hours).\n","title":"MVVM Material","type":"articles"},{"content":"When using WCF and Rest one thing you’re going to have to consider is the validation of the object, the way to do this is using the Validation Application Block included in the Microsoft Enterprise Library to validate the data transfer objects. This way you can decorate the objects with attributes to validated the objects\nHere is an example public static void Validate\u0026lt;T\u0026gt;(T obj)\n{\nValidationResults results = Validation.Validate(obj); if (!results.IsValid)\nstring[] errors = results\n.Select(r =\u0026gt; r.Message)\n.ToArray();\nWebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;\nWebOperationContext.Current.OutgoingResponse.StatusDescription = String.Concat(errors);\n}\nthanks to Enrico Campidoglio for helping out on this\n","date":"6 April 2010","externalUrl":null,"permalink":"/passing-validation-exceptions-via-wcf-rest/","section":"Articles","summary":"When using WCF and Rest one thing you’re going to have to consider is the validation of the object, the way to do this is using the Validation Application Block included in the Microsoft Enterprise Library to validate the data transfer objects. This way you can decorate the objects with attributes to validated the objects\n","title":"Passing Validation exceptions via WCF REST","type":"articles"},{"content":"It’s worth knowing how the Castle Windsor IoC work, by default it uses Singletons, where this will work for the most of the time, there are a lot more options available to you depending on your needs. These lifestyles that are available in Castle Windsor are:\nSingleton: components are instantiated once, and shared between all clients Transient: components are created on demand PerWebRequest: components are created once per Http Request Thread: components have a unique instance per thread Pooled: Optimization of transient components that keeps instance in a pool instead of always creating them Custom: allows you to specify a custom lifestyle… you’d have to specify a type that implements the ILifeStyleManager interface For further information on this take a look at Castle Windsors Lifestyles or Windsor and component instance lifetimes\n","date":"1 April 2010","externalUrl":null,"permalink":"/lifestyles-of-the-castle-windsor-ioc-containers/","section":"Articles","summary":"It’s worth knowing how the Castle Windsor IoC work, by default it uses Singletons, where this will work for the most of the time, there are a lot more options available to you depending on your needs. These lifestyles that are available in Castle Windsor are:\n","title":"Lifestyles of the Castle Windsor IoC Containers","type":"articles"},{"content":"With MVC 2 now released, I have found a nice little feature for updating models.\nThe normal practice is to use, a mapping technique like this\npublic void Save(EmployeeViewModel employeeViewModel)\n{\nvar employee = (from emp in dataContext.Employees\nwhere emp.EmployeeID == employeeViewModel.EmployeeID\nselect emp).SingleOrDefault();\nif (employee != null)\n{\nemployee.Address = employeeViewModel.Address;\nemployee.Salary = employeeViewModel.Salary;\nemployee.Title = employeeViewModel.Title;\n}\ndataContext.SubmitChanges();\n}\nBut now we can use the ModelCopier, which uses reflection to transpose the model\npublic void Save(EmployeeViewModel employeeViewModel)\n{\nvar employee = (from emp in dataContext.Employees\nwhere emp.EmployeeID == employeeViewModel.EmployeeID\nselect emp).SingleOrDefault();\nif (employee != null)\n{\nModelCopier.CopyModel(employeeViewModel, employee);\n}\ndataContext.SubmitChanges();\n}\nSo, you’ve tried it out, but you can’t find ModelCopier? That is because is part of MVC 2 futures, what a tease 😉\nI have however created this extended version of an Object Copier, which also copies objects inside of the object.\nObjectCopier.zip (50.83 kb)\n","date":"1 April 2010","externalUrl":null,"permalink":"/mvc-2-makes-it-easier-to-copy-models/","section":"Articles","summary":"With MVC 2 now released, I have found a nice little feature for updating models.\nThe normal practice is to use, a mapping technique like this\npublic void Save(EmployeeViewModel employeeViewModel)\n{\nvar employee = (from emp in dataContext.Employees\nwhere emp.EmployeeID == employeeViewModel.EmployeeID\nselect emp).SingleOrDefault();\n","title":"MVC 2 makes it easier to copy models","type":"articles"},{"content":"Dependency Injection (DI) is an incredibly useful and easy technique which makes your code a lot easier to test.\nI like to use samples to explain Dependency Injection. We’ll use a SqlMetaDataProvider class which needs to provide the meta data coming from a SQL Server database. It retrieves the meta data from the database in a relational structure (a DataSet) and then converts it to an easy to use object model. Obviously, i want to be able to test this class without actually going to the database because that would make the tests slow. So how can we test if the relational data is being converted to the object model without going to the database?\nWell, let’s look at what the class does. First of all, it retrieves sql server meta data. Then it converts it to an object model. But retrieving the meta data doesn’t really belong here… it should be functionality that’s offered by another class. So we create a SqlDataRetriever class. All it will do is return meta data in the relational structure. Nothing more. So now, our SqlMetaDataProvider class can simply use the SqlDataRetriever class to retrieve the meta data. So basically, SqlDataRetriever is now a dependency of the SqlMetaDataProvider class because SqlMetaDataProvider is depending on SqlDataRetriever to return the relational meta data.\nAt this point, our class could look like this:\npublic class SqlMetaDataProvider : IMetaDataProvider { private readonly string _connectionString; private readonly SqlDataRetriever _sqlDataRetriever; public SqlMetaDataProvider(string connectionString) { _connectionString = connectionString; _sqlDataRetriever = new SqlDataRetriever(); } public MetaDataStore GetMetaDataStore() { SqlMetaData sqlMetaData = _sqlDataRetriever.GetMetaData(_connectionString); return ConvertToMetaDataStore(sqlMetaData); } private MetaDataStore ConvertToMetaDataStore(SqlMetaData sqlMetaData) { MetaDataStore store = new MetaDataStore(); AddTablesToStore(sqlMetaData.TableInfo, store); AddColumnsToTablesInStore(sqlMetaData.ColumnInfo, store); CreateRelationshipsBetweenTables(sqlMetaData.RelationshipInfo, store); return store; } } Note: I left out the code for the AddTablesToStore, AddColumnsToTablesInStore and CreateRelationshipsBetweenTables methods because they aren’t relevant to this specific topic.\nNow we need to make sure we can replace the instance of SqlDataRetriever during testing with one we can supply ourselves. That test instance could then simply return a DataSet that was created in-memory, thus keeping our tests running fast. Notice how SqlMetaDataProvider has a reference of the type SqlDataRetriever. The type is essentially fixed, which creates a strong dependency on the SqlDataRetriever class. If we were to replace the type of the reference with an interface, it would at least make it easier to use another type for our required dependency, one that simply implements the interface.\nSo we create the ISqlDataRetriever interface:\npublic interface ISqlDataRetriever { SqlMetaData GetMetaData(string connectionString); } And then we modify the definition of SqlDataRetriever to implement the interface:\npublic class SqlDataRetriever : ISqlDataRetriever Now we need to modify our SqlMetaDataProvider class so it holds a reference to the interface type, instead of the class type:\nprivate readonly ISqlDataRetriever _sqlDataRetriever; We still need to find a way to inject our dependency into our SqlMetaDataProvider so we’ll modify the constructor:\npublic SqlMetaDataProvider(string connectionString, ISqlDataRetriever sqlDataRetriever) { _connectionString = connectionString; _sqlDataRetriever = sqlDataRetriever; } The only downside to this is that it now takes more work to create an instance of SqlMetaDataProvider… work that clients shouldn’t need to do if they just want to use the default ISqlDataRetriever implementation. If you’re using an Inversion Of Control (IoC) container, you can simply request an instance of SqlMetaDataProvider and the IoC container would also create the necessary dependency for you. Using an IoC container however is outside of the scope for this post, so we won’t do that. In fact, if you know that your production code will always use the SqlDataRetriever implementation, you could also provide a simpler constructor which takes care of that for you:\npublic SqlMetaDataProvider(string connectionString) : this(connectionString, new SqlDataRetriever()) {} So you could use the simpler constructor in your production code, and the other one in your test code. Speaking of test code, we still need to write that test which tests the conversion without hitting the database. First, we need to create an implementation of ISqlDataRetriever which allows us to pass a DataSet to it which the ISqlDataRetriever instance should return to its consumer (our SqlMetaDataProvider):\npublic class SqlDataProviderStub : ISqlDataRetriever { private SqlMetaData _sqlMetaData; public SqlMetaData SqlMetaData { set { _sqlMetaData = value; } } SqlMetaData ISqlDataRetriever.GetMetaData(string connectionString) { return _sqlMetaData; } } And finally, the test:\n[Test] public void GetMetaDataStore_ProvideDataSetWithTwoTablesAndRelationship_MetaDataStoreIsCorrect() { SqlMetaData sqlMetaData = PrepareMetaDataSetInMemoryWithTestData(); SqlDataProviderStub sqlDataProvider = new SqlDataProviderStub(); sqlDataProvider.SqlMetaData = sqlMetaData; // pass null as the connectionString, and pass our SqlDataProviderStub IMetaDataProvider metaDataProvider = new SqlMetaDataProvider(null, sqlDataProvider); MetaDataStore store = metaDataProvider.GetMetaDataStore(); AssertStoreContainsOurTestData(store); } Original article by Davy Brion ","date":"1 April 2010","externalUrl":null,"permalink":"/introduction-to-dependency-injection/","section":"Articles","summary":"Dependency Injection (DI) is an incredibly useful and easy technique which makes your code a lot easier to test.\nI like to use samples to explain Dependency Injection. We’ll use a SqlMetaDataProvider class which needs to provide the meta data coming from a SQL Server database. It retrieves the meta data from the database in a relational structure (a DataSet) and then converts it to an easy to use object model. Obviously, i want to be able to test this class without actually going to the database because that would make the tests slow. So how can we test if the relational data is being converted to the object model without going to the database?\n","title":"Introduction to Dependency Injection","type":"articles"},{"content":"With WCF now being around for some time, it supports many protocols, mainly SOAP, but it does also support Rest, the question is how do you do it? Well I have got the sample working from the MSDN Magazine. If you’d like the full detailed explaintation then you can go to An Introduction To RESTful Services With WCF MSDNMagazine.zip (64.82 kb)\n","date":"23 March 2010","externalUrl":null,"permalink":"/using-rest-via-wcf/","section":"Articles","summary":"With WCF now being around for some time, it supports many protocols, mainly SOAP, but it does also support Rest, the question is how do you do it? Well I have got the sample working from the MSDN Magazine. If you’d like the full detailed explaintation then you can go to An Introduction To RESTful Services With WCF ","title":"Using REST via WCF","type":"articles"},{"content":"Some times you need to cast from one object to the other, and then back again, the easiest way of doing this is using Interface casting, I’ve generated this simple project which show how it works.\nInterface Tests.zip (34.05 kb)\n","date":"19 March 2010","externalUrl":null,"permalink":"/casing-objects-using-interfaces/","section":"Articles","summary":"Some times you need to cast from one object to the other, and then back again, the easiest way of doing this is using Interface casting, I’ve generated this simple project which show how it works.\n","title":"Casing Objects using Interfaces","type":"articles"},{"content":"MVC 2 has been released, I’ve been developing an application using the RC and I am very happy with the new features, there are so many, Areas, Auto-Scaffold UI Helpers with Template Customization which I just love.\nI’ve just had to un-install my MVC 2 RC and install the official release of MVC 2 and it worked without any problems.\nNew Strongly Typed HTML Helpers Enhanced Model Validation support across both server and client Auto-Scaffold UI Helpers with Template Customization Support for splitting up large applications into “Areas” Asynchronous Controllers support that enables long running tasks in parallel Support for rendering sub-sections of a page/site using Html.RenderAction Lots of new helper functions, utilities, and API enhancements Improved Visual Studio tooling support To download click here\nFor more details check out Scott Gu’s blog on MVC 2 Released\n","date":"12 March 2010","externalUrl":null,"permalink":"/asp-net-mvc-2-released/","section":"Articles","summary":"MVC 2 has been released, I’ve been developing an application using the RC and I am very happy with the new features, there are so many, Areas, Auto-Scaffold UI Helpers with Template Customization which I just love.\n","title":"ASP.NET MVC 2 Released","type":"articles"},{"content":"Enums are a wonderful addition to .Net, but won’t it be nice to have a real world description that you can display to the user interface? Well you can, and here is how define an attribute (or use existing DisplayNameAttribute) and annotate your enum with names as additional meta-data:\npublic enum Unit\n{\n[DisplayName(“Hz”)] Hertz,\n[DisplayName(“%V”)] Volt\n}\n","date":"4 March 2010","externalUrl":null,"permalink":"/enums-with-real-world-names/","section":"Articles","summary":"Enums are a wonderful addition to .Net, but won’t it be nice to have a real world description that you can display to the user interface? Well you can, and here is how define an attribute (or use existing DisplayNameAttribute) and annotate your enum with names as additional meta-data:\n","title":"enums with real world names","type":"articles"},{"content":"I know that conditional breakpoints have been around for some time, I just keep forgetting how to set it, so I though it should be time write how to set a conditional breakpoint on my blog.\nWhen you only want to break under certain conditions, you can right-click on a breakpoint red circle (or go to the Breakpoints Window and bring up the context menu on a given breakpoint) and select Condition to bring up the dialog box for conditional breakpoints. You’re given two options: break only when the specified expression is true or break only when the specified value has changed. For this example, since I’m in a for loop, i’ll break when the value of result.Id == 22.\nYou’ll notice that the breakpoint circle now has a red plus on it to indicate it is conditional.\n","date":"3 March 2010","externalUrl":null,"permalink":"/conditional-breakpoints/","section":"Articles","summary":"I know that conditional breakpoints have been around for some time, I just keep forgetting how to set it, so I though it should be time write how to set a conditional breakpoint on my blog.\n","title":"Conditional Breakpoints","type":"articles"},{"content":"\n","date":"5 February 2010","externalUrl":null,"permalink":"/magic-mushrooms-make-everything-bigger-and-better/","section":"Articles","summary":"\n","title":"Magic Mushrooms Make Everything Bigger and Better","type":"articles"},{"content":"MVC 2 is ready for use and designed to work with both VS 2008, as well as with VS 2010. Click here to download the ASP.NET MVC 2 release candidate for .NET 3.5 and VS 2008. Nice thing is that it can be installed side-by-side with ASP.NET MVC on the same machine.\n","date":"29 January 2010","externalUrl":null,"permalink":"/asp-net-mvc-2-rc/","section":"Articles","summary":"MVC 2 is ready for use and designed to work with both VS 2008, as well as with VS 2010. Click here to download the ASP.NET MVC 2 release candidate for .NET 3.5 and VS 2008. Nice thing is that it can be installed side-by-side with ASP.NET MVC on the same machine.\n","title":"ASP.NET MVC 2 RC","type":"articles"},{"content":"Many a time you use the \u0026lt;a href’#’ title=’display a message’ /\u0026gt; to display a message when you want some hover over text to display additional information, which is fine, but what if you want to display some more fancy text, lets say in HTML you are stuck.\nSo I went on the search to find something that was easy to implement.\nI came across a number of different popups\noverLIB ToolTips by jQueryTools qtip SimpleTip Each having good coverage, but I ended up using overLIB mainly as Nadun at work found it very easy to use. Here is how I have implement the library I have implemented a simple jQuery version of the library, I am sure you could extend it to do a lot more, I always say KIS (Keep It Simple) Add a tag class of overlib and popup tag which holds the popup information, simple, e.g. \u0026lt;a href=”#” class=”overlib” popup=”Hello World”\u0026gt;Basic popup\u0026lt;/a\u0026gt; If you want to display HTML content in the popup, just added it to the popup tag \u0026lt;a href=”#” class=”overlib” popup=”\u0026lt;b\u0026gt;Bold\u0026lt;/b\u0026gt; can be displayed too”\u0026gt;HTML content\u0026lt;/a\u0026gt; I have also include in my sample the overlib_pagedefaults which sets a few things up for overLIB, but this is not required if you don’t want to use it. I have attached a fully working sample to make life easier. overLib.zip (71.66 kb)\n","date":"13 January 2010","externalUrl":null,"permalink":"/simple-popups-or-hover-overs/","section":"Articles","summary":"Many a time you use the \u003ca href’#’ title=’display a message’ /\u003e to display a message when you want some hover over text to display additional information, which is fine, but what if you want to display some more fancy text, lets say in HTML you are stuck.\n","title":"Simple popups or hover overs","type":"articles"},{"content":"When you are playing with Web Services you quite often find information held in an Attribute, but how do you get it out?\ne.g.\npublic enum Classification {\n[System.Xml.Serialization.XmlEnumAttribute(“Test drive demonstrator”)]\nTestdrivedemonstrator,\n[System.Xml.Serialization.XmlEnumAttribute(“Showroom vehicle”)]\nShowroomvehicle,\nBy using reflection you can gain access to the attribute, here is how:\nType enumType = typeof(velocityUom);\nforeach (FieldInfo fi in enumType.GetFields())\n{\nobject[] attrs = fi.GetCustomAttributes(typeof(XmlEnumAttribute), false);\nif (attrs.Length \u0026gt; 0)\n{\nConsole.WriteLine(((XmlEnumAttribute)attrs[0]).Name);\n}\n}\n","date":"8 January 2010","externalUrl":null,"permalink":"/how-do-you-retrieving-the-xmlenumattribute-values-for-an-enum/","section":"Articles","summary":"When you are playing with Web Services you quite often find information held in an Attribute, but how do you get it out?\ne.g.\npublic enum Classification {\n[System.Xml.Serialization.XmlEnumAttribute(“Test drive demonstrator”)]\nTestdrivedemonstrator,\n[System.Xml.Serialization.XmlEnumAttribute(“Showroom vehicle”)]\nShowroomvehicle,\nBy using reflection you can gain access to the attribute, here is how:\n","title":"How do you retrieving the XmlEnumAttribute values for an Enum","type":"articles"},{"content":"It’s a new year and it’s must be time for me to go over what toys I have played with in 2009.\nBalsamiq Mockups must be the best application and tool that I have come across this year, after giving a talk to DotNetDevNet on the application I found that many other developers went ahead and bought the application too. NotePad+, which is an extended version of the very basic default NotePad that comes with Windows. Just replace your NotePad with this one and off you go. SysInternals Process Explorer I have used every day, mainly due to the fact that Windows does not handle resources and memory that well, so you have to have a tool to sort it out for you when things go wrong. GhostDoc is an internal tool for use with Visual Studio and cuts down the amount of time required for documentation, and does it right all the time. The biggest and most impressive toy last year has to be the purchase of a MacBook, it’s so much easier than Windows 7, XP or Vista, and things just work as they should do, well designed and well throughout, this gets 10 out of 10 for last years toys. I’m sure I’ve used some other toys last year, but these are the ones that I remember the most. ","date":"4 January 2010","externalUrl":null,"permalink":"/last-years-toys/","section":"Articles","summary":"It’s a new year and it’s must be time for me to go over what toys I have played with in 2009.\nBalsamiq Mockups must be the best application and tool that I have come across this year, after giving a talk to DotNetDevNet on the application I found that many other developers went ahead and bought the application too. NotePad+, which is an extended version of the very basic default NotePad that comes with Windows. Just replace your NotePad with this one and off you go. SysInternals Process Explorer I have used every day, mainly due to the fact that Windows does not handle resources and memory that well, so you have to have a tool to sort it out for you when things go wrong. GhostDoc is an internal tool for use with Visual Studio and cuts down the amount of time required for documentation, and does it right all the time. The biggest and most impressive toy last year has to be the purchase of a MacBook, it’s so much easier than Windows 7, XP or Vista, and things just work as they should do, well designed and well throughout, this gets 10 out of 10 for last years toys. I’m sure I’ve used some other toys last year, but these are the ones that I remember the most.","title":"Last Years Toys","type":"articles"},{"content":"Having been using LINQ to SQL for some time now, I came across my very first issue “There is already an open DataReader associated with this Command which must be closed first.” it’s been some time since I had this issue.\nThe issue only appears on one database and that is being held on a SQL 2000 box.\nThe solution, sorry work around, is to transfer the results in to Lists using ToList() after each LINQ call.\nI have found it hard to replicate in my test environment, as it only happens on a clients installation.\nDavid Foderick posted a similar issue he had with the Entity Framework\nAfter speaking with Eric Nelson, he pointed out that SQL 2000 has a lack of support for MARS, however there is no planning to provide support for this, however SQL Azure does not allow MARS. So perhaps this issue will get addressed some time in the future?\n","date":"18 November 2009","externalUrl":null,"permalink":"/there-is-already-an-open-datareader-associated-with-this-command-which-must-be-closed-first/","section":"Articles","summary":"Having been using LINQ to SQL for some time now, I came across my very first issue “There is already an open DataReader associated with this Command which must be closed first.” it’s been some time since I had this issue.\n","title":"There is already an open DataReader associated with this Command which must be closed first.","type":"articles"},{"content":"After playing around with Combo boxes for a while within jQuery I thought it would be good to write down, mainly so I can remember how to find and play with properties from within jQuery. So here we go, here is the HTML that we’ll be using:\n\u0026lt;select id=”ComboBox” \u0026gt;\n\u0026lt;option value=”1″\u0026gt;Value 1\u0026lt;/option\u0026gt;\n\u0026lt;option value=”2″\u0026gt;Value 2\u0026lt;/option\u0026gt;\n\u0026lt;option value=”3″\u0026gt;Value 3\u0026lt;/option\u0026gt;\n\u0026lt;option value=”4″\u0026gt;Value 4\u0026lt;/option\u0026gt;\n\u0026lt;optgroup label=”Group1″\u0026gt;\n\u0026lt;option value=”5″\u0026gt;Value 5\u0026lt;/option\u0026gt;\n\u0026lt;option value=”6″\u0026gt;Value 6\u0026lt;/option\u0026gt;\n\u0026lt;option value=”7″\u0026gt;Value 7\u0026lt;/option\u0026gt;\n\u0026lt;option value=”8″\u0026gt;Value 8\u0026lt;/option\u0026gt;\n\u0026lt;/optgroup\u0026gt;\n\u0026lt;/select\u0026gt;\nGet the value of the selected item This is the easiest. Use the val method.\n$(“#ComboBox”).val()\nGet the text of the selected item If you just try using the text() method on the combobox, this will give you the text values of all of the options in a single string. Not what you want. The trick is to use the :selected query modifier on the option.\n$(“#ComboBox option:selected”).text()\nFind out when the select value changed This is also rather easy with JQuery.\n$(“#ComboBox”).change(function() { /* do something here */ });\nProgrammatically set the selected item. $(“#ComboBox”).val(2);\nModify the list. Modifying a select element is not fundamentally different than modifying any other element in the dom, but there are a few basics here to keep in mind. Mainly: try to avoid using the dom directly. Create html strings instead.\nClear the list: $(“#ComboBox”).html(“”);\nAdd to the list: $(“\u0026lt;option value=’9’\u0026gt;Value 9\u0026lt;/option\u0026gt;”).appendTo(“#ComboBox”);\nFor more information check out the jQuery API\n","date":"28 October 2009","externalUrl":null,"permalink":"/jquery-and-the-dropdownlist-combobox/","section":"Articles","summary":"After playing around with Combo boxes for a while within jQuery I thought it would be good to write down, mainly so I can remember how to find and play with properties from within jQuery. So here we go, here is the HTML that we’ll be using:\n","title":"JQuery and the DropDownList – ComboBox","type":"articles"},{"content":" Mike Taulty of Microsoft has now sorted out the Videos from the event Scott spoke at: –\nVisual Studio .NET\nSilverlight\nASP.NET MVC\n","date":"26 October 2009","externalUrl":null,"permalink":"/videos-of-scotts-sessions-at-the-manchester-guathon/","section":"Articles","summary":" Mike Taulty of Microsoft has now sorted out the Videos from the event Scott spoke at: –\nVisual Studio .NET\nSilverlight\nASP.NET MVC\n","title":"Videos of Scott’s sessions at the Manchester “Guathon”","type":"articles"},{"content":"It’s time for me to upgrade my development computer, in order to do this I have a few requests of my new partnership, mainly due to the fact that Windows 7 has been out for a while, well from MSDN, and it has made a huge step forwards being able to harness the power of the processor.\nFirst it’s got to be a processor worth having and I’m currently looking at the Intel Nehalem i7 920 S1366 2.66GHz (£213 from Dabs, or Amazon) or AMD Phenom II X3 720, which kicks arse on most processors that are out at the moment. This chip can be bought from Amazon at around £97.\nNext is the motherboard, which must support the ability for a lot of memory and support the AMD processor above, the Gigabyte MA790xt-ud4p, appears to do the job, and at £95 from Ebuyer.com. Or going for the Intel processor there is the Gigabyte S1366 Intel X58 DDR3 ATX Audio 2GbE Lan 3 Channel (£194 from Dabs)\nAs a developer you need to have a number of monitors, you need to see as much as you can to work efficiently, a graphics card that is capable of driving three if not more monitors is a must. The ATI-based graphics ATI Radeon™ HD 5870 graphics Graphics Card, is a mega graphics card and should support up to 3 monitors. This can be bought from Dabs costing around £299, what about this link too, it’s just starts to get confusing!\nNext and very importantly the machine must be 64bit and support Virtualization Technology, in order to use Microsoft Virtual PC in Windows 7 this has become a slight issue as not all processors support Virtualization. I came across a post by Marcus Yam, Which Intel CPUs Support XP Mode Virtualization?, which provides a good list of chips, also Intel provide a list of features for their chip sets, which is most helpful. Ed Bott has a good post too on How many Intel CPUs will fail the XP Mode test in Windows 7?. Apparently AMD has virtualization built into all 65nm and 45nm processors, so that makes it a little easier.\nWhat about the motherboards will they support Virtalization Technology? I’ve not managed to find this out yet.\nThe main hard drive is going to have the be a solid state hard drive, as I do like the idea of loading applications up in seconds, something like Crucial 64GB 2.5″ M225 SATAII Solid State Drive?, which comes in at £165, from Dabs, not bad for such blistering performance, the question is whether I RAID the drive or not? Not sure what the benefits would be to me, performance is not an issue with a solid state hard drive, and for reliability I am using Windows Home Server which backs up every night. Or am I missing something with RAID?\nThe file system to storing all my data is not really an issue as Terabyte hard drives are two a penny these days.\nNext is the memory I need to have about 8 Gbytes in order to perform fast Virtualization with the ability to expand further if I need to, I know the memory needs to be fast and what I’m not sure about yet is what type and speed do I need the memory to be? I’ve heard about Triple Channel and Dominator, but what is this all about? I’ve come across the Corsair (TR3X6G1866C9DF) 6GB DDR3 3X2GB DDR3-1866 CL 9-9-9-24 Triple Channel Memory Kit as £227 from Amazon a little high priced how ever very fast or another option is Corsair Memory DDR3 1333MHz 12GB Core I7 Supt, which appear to be good value at only £225 from Dabs.\nWith all the hardware I’m going to have to get a Power Supply Unit to drive it all, Corsair Memory 1000W ATX PSU (£160), and to house the kit it’s going to have to be a large desktop case (£85)\nOther accessories I will need also to make my machine, some Arctic Silver 5 3.5g Thermal Paste, Arctic Silver ArctiClean Thermal Material Remover \u0026amp; Surface Purifier 60ml Kit, and Nylon 6.6 Plain Washers, Colour : Natural, Thread Size : M5\nNext question is will all of the above work together?\nMy research has taken me many places and it all started at DotNetDevNet, with Jose and Guy helping me out.\nSo my search goes on.\n","date":"24 October 2009","externalUrl":null,"permalink":"/the-start-of-a-partnership/","section":"Articles","summary":"It’s time for me to upgrade my development computer, in order to do this I have a few requests of my new partnership, mainly due to the fact that Windows 7 has been out for a while, well from MSDN, and it has made a huge step forwards being able to harness the power of the processor.\n","title":"The start of a partnership","type":"articles"},{"content":"I was given the task of installing Team Foundation Server on a single server, and there are a few things to check and need to have installed before you can install\nFirst read and the supplied TFSInstall.chm install guide file. This is key – if you are new to the TFS install and do not follow the supplied “checklists” for your chosen set up, you will endure pain and agony. I pretty much tried to follow the install guide by the book, but below points out some specifics of our set up and the issues I came across.\nI install Windows Server 2003 on a Virtual Machine Install IIS Install SQL Server 2005 Standard Edition Install SQL Server 2005 Service Pack 2 Apply all the updates to Windows Downloaded en_visual_studio_team_system_2008_team_foundation_server_workgroup_x86_x64wow_dvd_X14-29253.iso from MSDN subscription and extracted the files. http://daveclarkesblog.blogspot.com/2008/07/installing-team-foundation-server-2008.html ","date":"23 October 2009","externalUrl":null,"permalink":"/team-foundation-server-2008-installing-on-a-single-server/","section":"Articles","summary":"I was given the task of installing Team Foundation Server on a single server, and there are a few things to check and need to have installed before you can install\nFirst read and the supplied TFSInstall.chm install guide file. This is key – if you are new to the TFS install and do not follow the supplied “checklists” for your chosen set up, you will endure pain and agony. ","title":"Team Foundation Server 2008 installing on a single server","type":"articles"},{"content":"I’ve been using the Microsoft Aspnetdb database for some time now, and I still get asked about how to create the database, so here you go enjoy:\nMicrosoft has a new and powerful default database schema in ASP.Net 2.0 as ASPNETDB.mdf database. This database file serves as a role provider, and membership provider. Visual Web Developer 2005 supports the ASP.Net configuration to manage this personal aspnetdb database file within the web application inside the App_Data folder. Aspnetdb database helps in managing users along with their roles e.g. admin, employee, editors etc. It also enables the in-built functionality of Login controls and web parts to be integrated on ASP.Net 2.0 web pages that helps in managing user profiles, login, and personalized user pages very easily even without writing the bulky code to implement the sql queries or stored procedures along with data access code for inserting, updating or deleting the user personalized data.\nHow to create Aspnetdb database? Using aspnet_regsql command:\nYou can use aspnet_regsql command to create aspnetdb database. This command executes the default scripts to create the default database for asp.net 2.0 web applications.\nSteps to create aspnetdb database using aspnet_regsql command:\nOpen the Visual Studio 2005 command prompt from Start –\u0026gt; All Programs –\u0026gt; Microsoft Visual Studio 2005 –\u0026gt; Visual Studio Tools –\u0026gt; Visual Studio 2005 Command Prompt\nType aspnet_regsql and press enter key This will open the ASP.Net SQL Server Setup wizard. Click next to continue… In the next screen select the option to Configure SQL Server for application services. This option executes a script to configure the database for managing user profiles, roles, membership and personalization. Click next to continue…\nIn this step enter the sql server name and choose the right authentication method. Leave the database field to default and click next… Confirm your settings and click next to finish. It’s also worth checking out: Creating the Application Services Database for SQL Server ","date":"11 October 2009","externalUrl":null,"permalink":"/how-do-i-create-the-aspnetdb-database/","section":"Articles","summary":"I’ve been using the Microsoft Aspnetdb database for some time now, and I still get asked about how to create the database, so here you go enjoy:\nMicrosoft has a new and powerful default database schema in ASP.Net 2.0 as ASPNETDB.mdf database. This database file serves as a role provider, and membership provider. Visual Web Developer 2005 supports the ASP.Net configuration to manage this personal aspnetdb database file within the web application inside the App_Data folder. Aspnetdb database helps in managing users along with their roles e.g. admin, employee, editors etc. It also enables the in-built functionality of Login controls and web parts to be integrated on ASP.Net 2.0 web pages that helps in managing user profiles, login, and personalized user pages very easily even without writing the bulky code to implement the sql queries or stored procedures along with data access code for inserting, updating or deleting the user personalized data.\n","title":"How do I create the aspnetdb database?","type":"articles"},{"content":"I’ve been working at home on and off for a number of year, and one thing that always comes up is how to collaborate with remote employees over the internet.\nI have been using Microsoft Shared View, it’s easy to use and just does the job. If you are using a Mac then you could also try out Microsoft Shared View for the Mac, although I have not tested this out yet.\nIt’s also worth check out How to Collaborate with Remote Employees with Office Communicator 2007 R2 by Scott Hanselman, for other ways for collaborate.\n","date":"7 October 2009","externalUrl":null,"permalink":"/how-to-collaborate-with-remote-employees/","section":"Articles","summary":"I’ve been working at home on and off for a number of year, and one thing that always comes up is how to collaborate with remote employees over the internet.\nI have been using Microsoft Shared View, it’s easy to use and just does the job. If you are using a Mac then you could also try out Microsoft Shared View for the Mac, although I have not tested this out yet.\n","title":"How to Collaborate with Remote Employees","type":"articles"},{"content":"Now that I’m using MVC fully it’s time to implement a Customer Error Page.\nAs ASP.NET MVC is a layer on top of ASP.NET we can still use the same Customer Errors that we are used to in the Web.Config, so just to make it SEO friendly, here is what it can look like:\n\u0026lt;customErrors mode=“On“ defaultRedirect=“~/Error/Unknown“ /\u0026gt;\nhttp://www.genericerror.com/blog/2009/01/27/ASPNetMVCCustomErrorPages/\nOther references worth check out are:\nASP.NET Custom Errors: Preventing 302 Redirects To Custom Error Pages\nBetter Custom Errors in ASP.NET\n404 vs 302 ASP.Net Custom Errors\n","date":"4 October 2009","externalUrl":null,"permalink":"/asp-net-mvc-custom-error-pages/","section":"Articles","summary":"Now that I’m using MVC fully it’s time to implement a Customer Error Page.\nAs ASP.NET MVC is a layer on top of ASP.NET we can still use the same Customer Errors that we are used to in the Web.Config, so just to make it SEO friendly, here is what it can look like:\n","title":"ASP.Net MVC Custom Error Pages","type":"articles"},{"content":"If you need to screen cast then check out Screen Toaster, it’s fast easy to use\nRegister \u0026amp; use it anywhere, anytime No download. Compatible with Windows, Mac OS X, Linux. Capture videos of onscreen action in one click Record screencasts, tutorials, demos, training, lectures and more. Share and stream videos online in Flash Embed them on blogs and webpages or send them by email. ","date":"4 October 2009","externalUrl":null,"permalink":"/fastest-way-to-screen-cast/","section":"Articles","summary":"If you need to screen cast then check out Screen Toaster, it’s fast easy to use\nRegister \u0026 use it anywhere, anytime No download. Compatible with Windows, Mac OS X, Linux. Capture videos of onscreen action in one click Record screencasts, tutorials, demos, training, lectures and more. Share and stream videos online in Flash Embed them on blogs and webpages or send them by email. ","title":"Fastest way to Screen Cast","type":"articles"},{"content":"If you need to script out the objects within a database, from generating tables through to extracting out the data so you can use it in another database or schema then you are going to need to script the SQL.\nMS SQL Server 2008 has new Generate Scripts option which enables you to script data in SQL Server database tables. you can script data from sql tables into a script file, to the clipboard or script data on a new sql query window. Script data can be used to export and/or import table data from one database to another database.\nThe Script Data option creates INSERT statements foreach row in the table using the column data that the related table record has. Later than the scripted table data can be used by executing the generated t-sql scripts, to create a copy of the original table on an other server or an other database with identical data or identical rows on the destination database or table, what’s more you can script the the database to go to a SQL 2000 database from a SQL 2008, how cool is that?\nSQL Server generate script with data is a powerful SQL Server tool in order to create sql script to move data from one database to another database.\nI want to demonstrate with a sample how a sql developer can use the Generate Scripts task in order to script table data of a SQL Server 2008 database table.\nOpen the Generate Scripts SubMenu Item from Task Menu\nFirst of all, open the Microsoft SQL Server Management Studio which is installed from the Client Tools of a MS SQL Server 2008 installation package.\nConnect to a MS SQL Server database instance using the Server Explorer or using the Connect screen.\nThen open the Object Explorer window and expand the Databases node.\nHere I connected to the local SQL Server instance and clicked over the Databases node and a list of existing sql server databases are visible in the object explorer window now. Later, I clicked the sql database MyWorks which owns the tables that I want to script data, rows/records of the database.\nContinue by right clicking on the database name and open the context menu, chooes Tasks menu and open submenu. Select Generate Script submenu item from the displated list.\nGenerate SQL Server Script Wizards\nWhen you select the Generate Scripts sub menu item the Generate SQL Server Scripts Wizard starts. SQL administrators and sql programmers can use the Script Wizard to generate t-sql scripts as a t-sql scripter to create scripts for any object (tables, views, schemas, etc). You can work in detail on the Script Wizard and find useful hint that you can benefit in your sql developments.\nWatch the following screen cast to see it in action.\n","date":"4 October 2009","externalUrl":null,"permalink":"/scripting-sql-objects-with-sql-2008/","section":"Articles","summary":"If you need to script out the objects within a database, from generating tables through to extracting out the data so you can use it in another database or schema then you are going to need to script the SQL.\n","title":"Scripting SQL Objects with SQL 2008","type":"articles"},{"content":"Came across this today, and thought it was very good.\nOriginal post\n","date":"25 September 2009","externalUrl":null,"permalink":"/one-day-in-kanban-land/","section":"Articles","summary":"Came across this today, and thought it was very good.\nOriginal post\n","title":"One day in Kanban land","type":"articles"},{"content":"An important tool when using MVC xVal version 1.0 is released, xVal is a validation helper for ASP.NET MVC that lets you use your own choice of server-side validation framework (e.g., Microsoft’s DataAnnotations attributes, or Castle Validator, or NHibernate Validaion) and dynamically generates client-side validation code from your rules.\nxVal 1.0\n","date":"18 September 2009","externalUrl":null,"permalink":"/xval-1-0-released/","section":"Articles","summary":"An important tool when using MVC xVal version 1.0 is released, xVal is a validation helper for ASP.NET MVC that lets you use your own choice of server-side validation framework (e.g., Microsoft’s DataAnnotations attributes, or Castle Validator, or NHibernate Validaion) and dynamically generates client-side validation code from your rules.\n","title":"xVal 1.0 released","type":"articles"},{"content":"When you are using MVC you will come across using the ModelState, and the most common use is ModelState.IsValid, if you’ve not used this before then check out Validating Model Data in an MVC Application or xVal – a validation framework for ASP.NET MVC, what I did come across is an exception beyound the normal checks, that a table was missing from the database. Although the error was recorded in the ModelState, it did not raise any exception and hence the exception handling did not capture the message. To record the Exception you’ll need to go over the collection and this code allows you to do this:\nforeach (var value in ModelState.Values)\n{\nforeach (var error in value.Errors )\n{\nthrow new Exception (error.ErrorMessage, error.Exception);\n}\n}\n","date":"18 September 2009","externalUrl":null,"permalink":"/modelstate-is-not-valid/","section":"Articles","summary":"When you are using MVC you will come across using the ModelState, and the most common use is ModelState.IsValid, if you’ve not used this before then check out Validating Model Data in an MVC Application or xVal – a validation framework for ASP.NET MVC, what I did come across is an exception beyound the normal checks, that a table was missing from the database. Although the error was recorded in the ModelState, it did not raise any exception and hence the exception handling did not capture the message. To record the Exception you’ll need to go over the collection and this code allows you to do this:\n","title":"ModelState is not Valid","type":"articles"},{"content":"I’ve been playing with Windows 7 for a little while now and I am impressed it lokks like Microsoft have got it right. I’m a power user and if it works for me I can say it is going to work for Mr Average Joe. I’d thought I draw up a number of special features that I have found in my travels around Windows 7.\nProblem Steps Recorder You can use Problem Steps Recorder to automatically capture the steps you take on a computer, including a text description of where you clicked and a picture of the screen during each click (called a screen shot). Once you capture these steps, you can save them to a file that can be used by a support professional or someone else helping you with a computer problem.\nTo start type PSR in the Start menu search box\nMore details from Tech Republic\nProblem Steps Recorder with Jeremy Chapman\nISO Burner You now have the ability directly from within Windows 7 to burn ISO images directly to CD or DVD, if you’d like to know how to do it check out Burn ISO Images Natively in Windows 7 Burn ISO Images Natively in Windows 7\nSwitch to a projector Windows 7 now provides a standard way to switch your display from one monitor to another, or a projector – just press Win+P or run DisplaySwitch.exe and choose your preferred display. Calibrating your screen I’ve done this before using Windows Media Centre, nand now you can calibrate your screen by running Display Colour Calibration Wizard, Click Start, type DCCW and press Enter to give it a try.\nRicht-Click If you’ve not already tried this Right-Click has come it to it’s own with so many features available, and making it so much faster to perform your day to day actions\nCustom power switch By default, Windows 7 displays a plain text ‘Shut down’ button on the Start menu, but it only takes a moment to change this action to something else. If you reboot your PC a few times every day then that might make more sense as a default action: right-click the Start orb, select Properties and set the ‘Power boot action’ to ‘Restart’ to make it happen.\nGive the menu bar a shake If you shake the menu bar all the other windows minimize, how cool is that?\nIf you have multiple windows open on your desktop and things are getting too cluttered, it used to be a time-consuming process to close them all down. In Windows 7 you can use the Aero Shake feature to minimise everything in seconds, using a cool mouse gesture. Grab the title bar of the window you wish to keep open and give it a shake, and rejoice in a clear desktop area.\nUse Sticky Notes The Sticky Notes app is both simpler and more useful in Windows 7. Launch StikyNot.exe and you can type notes at the keyboard; right-click a note to change its colour; click the + sign on the note title bar to add another note; and click a note and press Alt + 4 to close the note windows.\nRSS-powered Windows 7 desktop slideshowsRSS-powered Windows 7 desktop slideshows Now have the power to change your desktop via RSS feeds, click here to see how to do it\nKeyboard shortcuts Windows 7 supports several useful new keyboard shortcuts.\nAlt+P\nDisplay/ hide the Explorer preview pane\nWindows Logo+G\nDisplay gadgets in front of other windows\nWindows Logo++ (plus key)\nZoom in, where appropriate\nWindows Logo+- (minus key)\nZoom out, where appropriate\nWindows Logo+Up Maximise the current window\nWindows Logo+Down\nMinimise the current window\nWindows Logo+Left\nSnap to the left hand side of the screen\nWindows Logo+Right\nSnap to the right hand side of the screen\nWindows Logo+Home\nMinimise/ restore everything except the current window\nMulti-threaded Robocopies An excellent command-line robocopy tool with new switches introduced with Windows 7. Check out, /MT, can improve speed by carrying out multi-threaded copies with the number of threads you specify. Enter robocopy /? at a command line for the full details.\n","date":"12 September 2009","externalUrl":null,"permalink":"/windows-7-things-you-dont-know/","section":"Articles","summary":"I’ve been playing with Windows 7 for a little while now and I am impressed it lokks like Microsoft have got it right. I’m a power user and if it works for me I can say it is going to work for Mr Average Joe. I’d thought I draw up a number of special features that I have found in my travels around Windows 7.\n","title":"Windows 7 – things you don’t know","type":"articles"},{"content":"Need to know how to write easy to look after XML code, check out the the DNRTV\nhttp://perseus.franklins.net/dnrtvplayer/player/?ShowNum=0147\nThe source code can be download here LINQXMLSamples.zip (112.26 kb)\n","date":"2 September 2009","externalUrl":null,"permalink":"/linq-to-xml/","section":"Articles","summary":"Need to know how to write easy to look after XML code, check out the the DNRTV\nhttp://perseus.franklins.net/dnrtvplayer/player/?ShowNum=0147\nThe source code can be download here LINQXMLSamples.zip (112.26 kb)\n","title":"LINQ to XML","type":"articles"},{"content":"http://www.ssmstoolspack.com/\n","date":"30 August 2009","externalUrl":null,"permalink":"/generating-sql-insert-statement/","section":"Articles","summary":"http://www.ssmstoolspack.com/\n","title":"Generating SQL Insert Statement","type":"articles"},{"content":"I needed a simple way of editing the text on the screen, without the need to open up or view a second screen, so I had a look around for some jQuery, and came across this very good jQuery plugin from Mika Tuupola, jEditable\nFor a live demo of jEditable click here\nI am just so impressed with what you can do with jQuery, it’s making JavaScript work the way it should have done all those years ago.\n","date":"20 August 2009","externalUrl":null,"permalink":"/inline-editing/","section":"Articles","summary":"I needed a simple way of editing the text on the screen, without the need to open up or view a second screen, so I had a look around for some jQuery, and came across this very good jQuery plugin from Mika Tuupola, jEditable\n","title":"Inline Editing","type":"articles"},{"content":"Came across this nice article on different uses for your USB flash drive\nTransporting your data is probably the most common use for a USB flash drive. But there’s a world of other things you can do with these handy pocket-size drives. Here are 10 ways you can use that USB flash drive to do more than just move data\n1: Run portable applications In addition to storing your data, you can run portable applications from a USB flash drive. For example, OpenOffice, which is a complete office suite that includes a word processor, spreadsheet, presentation tool, drawing package, and database, is available as a portable application. Mozilla Firefox and Thunderbird are also available as portable applications. When you combine the office suite with the ability to surf the Web and check email, you’ll be able to take your most vital computing applications with you wherever you go — right in your pocket.\nIf that’s not enough, you can choose other applications to install on your USB flash drive from PortableApps.com (Figure A). You can even install an entire prepackaged suite of applications that includes such things as an audio player, games, an antivirus utility, and a handy menu system.\nFigure A The PortableApps.com suite comes with a menu system to allow you to easily access your portable applications. 2: Boot an operating system If you want to do more than just run your own applications, you might want to consider booting an entire operating system from your USB flash drive. You can boot either Windows or Linux from a USB flash drive; however, the process is not an exact science and you may be in for a technical adventure.\nFortunately, there are some guides you can follow. To learn how to boot Windows XP from a USB flash drive, see the article Creating a bootable USB flash drive for Windows XP. To learn how to boot a version of Linux from a USB flash drive, see the articlePuppy Linux teaches an old dog new tricks.\n3: Connect to a wireless network If you have a wireless network, you can use the Wireless Network Setup Wizard in Windows XP or the Windows Connect Now (WCN) feature built into Vista to save wireless network configuration information to a USB flash drive. You can then use your drive to quickly and easily connect another computer or a WCN-compatible device, such as a router or printer, to your wireless network. To learn more about using the Wireless Network Setup Wizard, see the Help And Support Center, which is accessible from Windows XP’s Start menu. To learn more about using the Windows Connect Now feature, see Windows Help And Support, which is accessible from Windows Vista’s Start menu.\n4: Create a password reset disk A password reset disk can really come in handy if you forget the password to your user account on a Windows system that is not a part of a domain. If you find yourself in that situation, you can use the password reset disk to reset your password and quickly get back into your user account. In Windows Vista, you can use USB flash drive rather than a floppy disk as a password reset disk (Figure B). For details on how to do so, see the article Create a Vista password reset disk using a USB flash drive.\nFigure B You can use your USB flash drive as a password reset disk. 5: Boost performance If you’re running Windows Vista, you can use a USB flash drive to speed up your system with the ReadyBoost technology. ReadyBoost can use the storage space on a USB Flash drive as an additional memory cache to aid the memory cache on your hard disk. And because flash memory is more responsive than a hard disk, with its physical moving parts, the memory cache provided by ReadyBoost can significantly improve system responsiveness.\nUsing ReadyBoost is easy. You just insert your USB flash drive into your Vista system and follow the onscreen prompts to configure and use ReadyBoost. If you want more details, check out the article How SuperFetch and ReadyBoost work together.\n6: Manage it If all you really want to do with your USB flash drive is transport data, and you’re running Windows XP, you can do so more efficiently with the Microsoft USB Flash Drive Manager (Figure C). Once you have installed this manager, you can easily copy files to and from your drive, back up and restore the entire flash drive to and from your hard disk, change the drive label, and even create an autorun.inf file to launch Drive Manager automatically when you plug in the drive. To learn more about and download the USB Flash Drive Manager visit the Microsoft TechNet Magazine site.\nFigure C The Microsoft USB Flash Drive Manager provides you with a host of features, such as drive backup. 7: Use it as an MP3 player Would you like to be listening to music when you’re using a computer at the office, but you don’t have an MP3 player? If so, you can use a USB flash drive as an MP3 player along with Windows Media Player and a set of headphones. Just copy your MP3 files to your USB flash drive, plug it into your computer, and direct Windows Media Player to build a library of the songs on your drive. You can use all of Windows Media Player’s playback features, such as playlists and favorites, to easily customize your music listening experience. And best of all, you won’t have to worry about running low on battery power.\n8: Password-protect it If you use a USB flash drive to transport sensitive data that you would prefer to protect from prying eyes, should you lose the drive, Rohos Mini Drive (Figure D) can safeguard that data. This security tool allows you to create a secret partition on the drive and then password-protect/encrypt that partition, thus protecting any documents you copy to that partition via the utility’s file manager. You can download (and read a review of) Rohos Mini Drive at Download.com.\nFigure D Using Rohos Mini Drive, you can secure sensitive files on your USB flash drive. 9: Run a Web site from it If you are a Web developer, you may be interested to know that with Server2Go, you can easily run a Web server that supports Apache, PHP, MySQL, and Perl right from a USB flash drive. You can use Server2Go right out of the box without any installation. It runs on all versions of Windows, supports most common browsers, and is completely free. To a developer, the benefits of having a portable Web server on a USB drive are numerous. For example, imagine being able to carry a live Web site demo into a sales pitch meeting. For more information about this package, visit the Server2Go site.\n10: Lock your PC Have you ever seen a movie in which a person in some secret government installation simply inserts and removes a card to log in and log out of a PC? If you thought that idea was cool, you’ll definitely want to investigate Predator (Figure E). Once installed and configured, this little freeware utility will allow you to turn a USB flash drive into a key you can use to lock and unlock your computer.\nFigure E With Predator, you can use a USB flash drive as a key to lock and unlock your computer. While the USB flash drive is connected to your computer, everything works as it normally would. Once you remove the USB flash drive, your computer is locked down — the keyboard and mouse are disabled and the screen darkens. To unlock your computer, you just plug in the USB flash drive and the computer will be unlocked and you can begin using it. To learn more about Predator, and/or to download it, visit the developer’s Web site.\nTechRepublic – 5th August 2009\n","date":"12 August 2009","externalUrl":null,"permalink":"/10-cool-things-you-can-do-with-a-usb-flash-drive/","section":"Articles","summary":"Came across this nice article on different uses for your USB flash drive\nTransporting your data is probably the most common use for a USB flash drive. But there’s a world of other things you can do with these handy pocket-size drives. Here are 10 ways you can use that USB flash drive to do more than just move data\n","title":"10 cool things you can do with a USB flash drive","type":"articles"},{"content":"\n","date":"3 August 2009","externalUrl":null,"permalink":"/if-browsers-were-women/","section":"Articles","summary":"\n","title":"If Browsers were women","type":"articles"},{"content":"The first of the next version of MVC 2 has been release by Microsoft, a few nice features, which has extended the Html helpers.\nThe full release will be shipped with Visual Studio 2010, and a version will be available for download for Visual Studio 2008 sp1 at the same time.\nWhy not watch it on Channel 9 – ASP.NET MVC 2 Preview 1 with Phil Haack and Virtual Scott\nFor more details check out Haacked ","date":"31 July 2009","externalUrl":null,"permalink":"/mvc-2-preview-1/","section":"Articles","summary":"The first of the next version of MVC 2 has been release by Microsoft, a few nice features, which has extended the Html helpers.\nThe full release will be shipped with Visual Studio 2010, and a version will be available for download for Visual Studio 2008 sp1 at the same time.\n","title":"MVC 2 Preview 1","type":"articles"},{"content":"Where are those extra features that did not quite make it in the initial release of ASP.MVC 1.0, they can be found on Code Plex, ASPNET\nASP.NET MVC Futures – Microsoft.Web.Mvc The following are a few items in the ASP.NET MVC Futures assembly:\nAsyncController ButtonBuilder Html.Substitute CacheExtension FileCollectionModelBinder LinqBinaryModelBinder Html.Mailto Helpers SkipBindingAttribute RequireSslAttribute AcceptAjaxAttribute Html.RenderAction and Html.RenderRoute Extensions Repeater Control ByteArrayModelBinder and more, for more details check out Maarten Balliauw Blog Microsoft.Web.Mvc.dll (103.50 kb) ","date":"17 July 2009","externalUrl":null,"permalink":"/asp-net-mvc-futures/","section":"Articles","summary":"Where are those extra features that did not quite make it in the initial release of ASP.MVC 1.0, they can be found on Code Plex, ASPNET\nASP.NET MVC Futures – Microsoft.Web.Mvc The following are a few items in the ASP.NET MVC Futures assembly:\n","title":"ASP.NET MVC Futures","type":"articles"},{"content":" After a great DDD South West, now comes the video, great production, setting a high standard for years to come\nDDD South West Video\n","date":"15 July 2009","externalUrl":null,"permalink":"/ddd-south-west-video/","section":"Articles","summary":" After a great DDD South West, now comes the video, great production, setting a high standard for years to come\n","title":"DDD South West Video","type":"articles"},{"content":"If and when you have to deploy your MVC application, you’ll soon find out that IIS6 does not support Url Rewriting. There are a number of options available to you, for a good list check out Steve Sanderson’s Deploying ASP.NET MVC to IIS 6, the one I’m currently using is:\nUse a wildcard mapping for aspnet_isapi.dll This tells IIS 6 to process all requests using ASP.NET, so routing is always invoked, and there’s no problem. It’s dead easy to set up: open IIS manager, right-click your app, go to Properties, then Home Directory tab, then click Configuration. Under Wildcard application maps, click Insert (not Add, which is confusingly just above), then enter C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_isapi.dll for “Executable”, and uncheck Verify that file exists.\nDone! Routing now just behaves as it always did in VS2008’s built-in server.\nUnfortunately, this also tells IIS to use ASP.NET to serve all requests, including for static files. It will work, because ASP.NET has a built-in DefaultHttpHandler that does it, but depending on what you do during the request, it might use StaticFileHandler to serve the request. StaticFileHandler is much less efficient than IIS natively. You see, it always reads the files from disk for every request, not caching them in memory. It doesn’t send Cache-Control headers that you might have configured in IIS, so browsers won’t cache it properly. It doesn’t do HTTP compression. However, if you can avoid interfering with the request, DefaultHttpHandler will pass control back to IIS for native processing, which is much better.\nFor small intranet applications, wildcard mappings are probably the best choice. Yes, it impacts performance slightly, but that might not be a problem for you. Perhaps you have better things to worry about.\nFor larger public internet applications, you may need a solution that delivers better performance.\nSnippet taken from Steve Sanderson’s Deploying ASP.NET MVC to IIS 6\nFor more information take a look at ScottGu’s blog, Tip/Trick: Url Rewriting with ASP.NET\nAlso worth taking a look at Phil Haacked articles on ASP.NET MVC on IIS 6 Walkthrough\n","date":"2 July 2009","externalUrl":null,"permalink":"/deploying-mvc-on-iis-6/","section":"Articles","summary":"If and when you have to deploy your MVC application, you’ll soon find out that IIS6 does not support Url Rewriting. There are a number of options available to you, for a good list check out Steve Sanderson’s Deploying ASP.NET MVC to IIS 6, the one I’m currently using is:\n","title":"Deploying MVC on IIS 6","type":"articles"},{"content":"\nA comprehensive list of culture codes used for localising and in conjunction with the CultureInfo class.\nThe CultureInfo class specifies a unique name for each culture, based on RFC 4646 (Windows Vista and later). The name is a combination of an ISO 639 two-letter lowercase culture code associated with a language and an ISO 3166 two-letter uppercase subculture code associated with a country or region.\nCode Language – Country/Region Code Language – Country/Region af Afrikaans hu-HU Hungarian – Hungary af-ZA Afrikaans – South Africa is Icelandic sq Albanian is-IS Icelandic – Iceland sq-AL Albanian – Albania id Indonesian ar Arabic id-ID Indonesian – Indonesia ar-DZ Arabic – Algeria it Italian ar-BH Arabic – Bahrain it-IT Italian – Italy ar-EG Arabic – Egypt it-CH Italian – Switzerland ar-IQ Arabic – Iraq ja Japanese ar-JO Arabic – Jordan ja-JP Japanese – Japan ar-KW Arabic – Kuwait kn Kannada ar-LB Arabic – Lebanon kn-IN Kannada – India ar-LY Arabic – Libya kk Kazakh ar-MA Arabic – Morocco kk-KZ Kazakh – Kazakhstan ar-OM Arabic – Oman kok Konkani ar-QA Arabic – Qatar kok-IN Konkani – India ar-SA Arabic – Saudi Arabia ko Korean ar-SY Arabic – Syria ko-KR Korean – Korea ar-TN Arabic – Tunisia ky Kyrgyz ar-AE Arabic – United Arab Emirates ky-KG Kyrgyz – Kyrgyzstan ar-YE Arabic – Yemen lv Latvian hy Armenian lv-LV Latvian – Latvia hy-AM Armenian – Armenia lt Lithuanian az Azeri lt-LT Lithuanian – Lithuania az-AZ-Cyrl Azeri (Cyrillic) – Azerbaijan mk Macedonian az-AZ-Latn Azeri (Latin) – Azerbaijan mk-MK Macedonian – Former Yugoslav Republic of Macedonia eu Basque ms Malay eu-ES Basque – Basque ms-BN Malay – Brunei be Belarusian ms-MY Malay – Malaysia be-BY Belarusian – Belarus mr Marathi bg Bulgarian mr-IN Marathi – India bg-BG Bulgarian – Bulgaria mn Mongolian ca Catalan mn-MN Mongolian – Mongolia ca-ES Catalan – Catalan no Norwegian zh-HK Chinese – Hong Kong SAR nb-NO Norwegian (Bokm?l) – Norway zh-MO Chinese – Macao SAR nn-NO Norwegian (Nynorsk) – Norway zh-CN Chinese – China pl Polish zh-CHS Chinese (Simplified) pl-PL Polish – Poland zh-SG Chinese – Singapore pt Portuguese zh-TW Chinese – Taiwan pt-BR Portuguese – Brazil zh-CHT Chinese (Traditional) pt-PT Portuguese – Portugal hr Croatian pa Punjabi hr-HR Croatian – Croatia pa-IN Punjabi – India cs Czech ro Romanian cs-CZ Czech – Czech Republic ro-RO Romanian – Romania da Danish ru Russian da-DK Danish – Denmark ru-RU Russian – Russia div Dhivehi sa Sanskrit div-MV Dhivehi – Maldives sa-IN Sanskrit – India nl Dutch sr-SP-Cyrl Serbian (Cyrillic) – Serbia nl-BE Dutch – Belgium sr-SP-Latn Serbian (Latin) – Serbia nl-NL Dutch – The Netherlands sk Slovak en English sk-SK Slovak – Slovakia en-AU English – Australia sl Slovenian en-BZ English – Belize sl-SI Slovenian – Slovenia en-CA English – Canada es Spanish en-CB English – Caribbean es-AR Spanish – Argentina en-IE English – Ireland es-BO Spanish – Bolivia en-JM English – Jamaica es-CL Spanish – Chile en-NZ English – New Zealand es-CO Spanish – Colombia en-PH English – Philippines es-CR Spanish – Costa Rica en-ZA English – South Africa es-DO Spanish – Dominican Republic en-TT English – Trinidad and Tobago es-EC Spanish – Ecuador en-GB English – United Kingdom es-SV Spanish – El Salvador en-US English – United States es-GT Spanish – Guatemala en-ZW English – Zimbabwe es-HN Spanish – Honduras et Estonian es-MX Spanish – Mexico et-EE Estonian – Estonia es-NI Spanish – Nicaragua fo Faroese es-PA Spanish – Panama fo-FO Faroese – Faroe Islands es-PY Spanish – Paraguay fa Farsi es-PE Spanish – Peru fa-IR Farsi – Iran es-PR Spanish – Puerto Rico fi Finnish es-ES Spanish – Spain fi-FI Finnish – Finland es-UY Spanish – Uruguay fr French es-VE Spanish – Venezuela fr-BE French – Belgium sw Swahili fr-CA French – Canada sw-KE Swahili – Kenya fr-FR French – France sv Swedish fr-LU French – Luxembourg sv-FI Swedish – Finland fr-MC French – Monaco sv-SE Swedish – Sweden fr-CH French – Switzerland syr Syriac gl Galician syr-SY Syriac – Syria gl-ES Galician – Galician ta Tamil ka Georgian ta-IN Tamil – India ka-GE Georgian – Georgia tt Tatar de German tt-RU Tatar – Russia de-AT German – Austria te Telugu de-DE German – Germany te-IN Telugu – India de-LI German – Liechtenstein th Thai de-LU German – Luxembourg th-TH Thai – Thailand de-CH German – Switzerland tr Turkish el Greek tr-TR Turkish – Turkey el-GR Greek – Greece uk Ukrainian gu Gujarati uk-UA Ukrainian – Ukraine gu-IN Gujarati – India ur Urdu he Hebrew ur-PK Urdu – Pakistan he-IL Hebrew – Israel uz Uzbek hi Hindi uz-UZ-Cyrl Uzbek (Cyrillic) – Uzbekistan hi-IN Hindi – India uz-UZ-Latn Uzbek (Latin) – Uzbekistan hu Hungarian vi Vietnamese ","date":"19 June 2009","externalUrl":null,"permalink":"/culture-codes/","section":"Articles","summary":"\nA comprehensive list of culture codes used for localising and in conjunction with the CultureInfo class.\n","title":"Culture Codes","type":"articles"},{"content":" I recently ran into the altogether common problem of the Html.DropDownList helper rendering a drop down list with no value selected. This is a major problem when editing data as by default, the first value is selected and saving would mean the first value is used.\nThere have been a few issues resulting in the same error. My issue was that I was setting the Name of the drop down list to be equal to the property on my model. I was using the Entity Framework, and had an Image class with a navigation property called Category. I was using this to render the ddl:\n\u0026lt;%= Html.DropDownList(“Category”, (IEnumerable\u0026lt;SelectListItem\u0026gt;)ViewData[“categories”])%\u0026gt;\nIn my controller, I was setting the ViewData like this:\nthis.ViewData[“categories”] = new SelectList(db.CategorySet.ToList(), “CategoryId”, “Title”, img.CategoryReference.EntityKey);\nUnfortunately, even though I had set the selected value (third parameter to the SelectList constructor), the ddl had no value selected.\nThe fix was quite simple:\n\u0026lt;%= Html.DropDownList(“CategoryId”, (IEnumerable\u0026lt;SelectListItem\u0026gt;)ViewData[“categories”])%\u0026gt;\nI just changed the Name of the drop down and handled the assignment in the controller.\nThe reason behind this problem is that asp.net MVC first looks for a match between the name of the drop down and a property on the model. If there’s a match, the selected value of the SelectList is overridden. Changing the name of the drop down is all it takes to remedy the issue.\n","date":"18 June 2009","externalUrl":null,"permalink":"/asp-net-mvc-html-dropdownlist-and-selected-value/","section":"Articles","summary":" I recently ran into the altogether common problem of the Html.DropDownList helper rendering a drop down list with no value selected. This is a major problem when editing data as by default, the first value is selected and saving would mean the first value is used.\n","title":"Asp.net MVC, Html.DropDownList and Selected Value","type":"articles"},{"content":"If you are like me, I like to keep my Visual Studio environment as clean as possible, so if I can get away from adding any addins in to Visual Studio I will always go for that option.\nSo when it comes to testing I prefer to run with NUnit and run it as n external program. To do this just right click on the unit test project -\u0026gt; choosing the properties option -\u0026gt; setecting the Debug tab -\u0026gt; choose “start external program” and enter the NUnit assembly path, in my case this is “C:\\Program Files\\NUnit 2.5\\bin\\net-2.0\\nunit.exe”, next is to select the command line arguments and point this to your unit test dll,\ne.g. “C:\\Program Files\\NUnit 2.5\\samples\\csharp\\money\\bin\\Debug\\cs-money.dll” /run\nThe “run” parameter will automatically run the loaded project\nAlternatively you can use a Visual Studio add-in such as TestDriven.Net, this also provides NCoverExplorer to provide you with code coverage.\n","date":"15 June 2009","externalUrl":null,"permalink":"/running-nunit-from-visual-studio/","section":"Articles","summary":"If you are like me, I like to keep my Visual Studio environment as clean as possible, so if I can get away from adding any addins in to Visual Studio I will always go for that option.\n","title":"Running NUnit from Visual Studio","type":"articles"},{"content":"When you open up MVC out of the box, you get the basic configuration, after a little playing around you soon see areas that require enhancing to, not only make your application more flexable, but also easier to maintain.\nHere are a number of additional tasks you can perform that will help with your application.\nWhich IoC to use? Don’t worry, if you use the Common Service Locator it provides an adstraction over the IoC\nHow to validate? I have already covered this one in a previous post, but I’d still go with xVal\nNeed to generate Themes? I think it is so important to start correctly and generating the User Interface should be configurable, the easiest way of doing this is to implement a Theme, and Chris Pietschmann has do this for us, Implement Theme Folders using a Custom ViewEngine\nHere is a copy of the source for safe keeping.\nASPNETMVC_Preview5_CustomThemeImplementation.zip (226.05 kb)\nNeed Ajax to work in MVC Ajax.BeginForm and PartialViews\nExtend the UrlHelper Placing all your assets in one place is not only a good idea, but it also means you can be more flexable if you want to programmically change the theme of your user interface.\nWhich can be used like this:\nUsing Strongtypes and keep away from Strings It appears so easy with MVC to use String everywhere, just DON’T, generate an extension for the UrlHelper\nNow in your view it will look like this\nTesting I’ve been hit before by Microsofts in build Testing within Visual Studio 2008, great to have this feature built in, BUT, and a big but in order to run the tests you need to have Visual Studio install, so if you try and setup a Continuous Integration server you will also be required to install Visual Studio.\nSo best to go with what works well and that is nUnit, simple and easy, and more importantly loosely coupled\nMocking With testing comes Mocking, and which framework do you use? I also always say keep it simple and easy, so I’m going with Moq, short for “Mock-You”, as this is the only Mock Framework that is built around .Net 3.5 and LINQ.\n","date":"10 June 2009","externalUrl":null,"permalink":"/building-up-an-mvc-application/","section":"Articles","summary":"When you open up MVC out of the box, you get the basic configuration, after a little playing around you soon see areas that require enhancing to, not only make your application more flexable, but also easier to maintain.\n","title":"Building up an MVC application","type":"articles"},{"content":"Validation is such an important part of development, and the best way I have found for the MVC is by Steven Sanderson, xVal, which is a validation framework for ASP MVC, even Scott Gu thinks it is absolutely fantastic.\nIf you are after using xVal with Linq to SQL then it is well worth checking out Integrating xVal Validation with Linq-to-Sql by Adam Schroder\nIt’s worth checking out Client-side form validation made easy by Adrian Grigore to extend this validation even further.\nDon’t take my word for is, check out, ASP.NET MVC Validation Refresh: Best Techniques \u0026amp; Frameworks by Graham O’Neale\n","date":"10 June 2009","externalUrl":null,"permalink":"/mvc-validation/","section":"Articles","summary":"Validation is such an important part of development, and the best way I have found for the MVC is by Steven Sanderson, xVal, which is a validation framework for ASP MVC, even Scott Gu thinks it is absolutely fantastic.\n","title":"MVC Validation","type":"articles"},{"content":"\n","date":"1 June 2009","externalUrl":null,"permalink":"/scrum-the-story/","section":"Articles","summary":"\n","title":"Scrum the story","type":"articles"},{"content":"I was wondering today if anyone had produced any benchmarks on the speed and performance of LINQ, so I had a look around and found that LINQ 2 SQL is 4 times faster than the Entity Framework. Why is this? It is due the the fact that the Entity Framework is a more generic solution, where as LINQ to SQL can be more fine tuned to the underlying database structure.\nHere are a few links I found that might explain things in more details\nADO.NET Entity Framework Performance Comparison\nHow Slow is ‘Slow’?\n","date":"26 May 2009","externalUrl":null,"permalink":"/speed-and-performance-of-linq/","section":"Articles","summary":"I was wondering today if anyone had produced any benchmarks on the speed and performance of LINQ, so I had a look around and found that LINQ 2 SQL is 4 times faster than the Entity Framework. Why is this? It is due the the fact that the Entity Framework is a more generic solution, where as LINQ to SQL can be more fine tuned to the underlying database structure.\n","title":"Speed and Performance of LINQ","type":"articles"},{"content":"There are many ways of managing a Scrum Sprint, but I always look for the easy ways, I came across Deborah Hartmann, spreadsheet which I have found very useful and easy to get along with. Once you understand the processes of Scrum and what is required the spreadsheet speak a thousand words.\nSprint Backlog\n","date":"26 May 2009","externalUrl":null,"permalink":"/managing-sprints-in-a-scrum/","section":"Articles","summary":"There are many ways of managing a Scrum Sprint, but I always look for the easy ways, I came across Deborah Hartmann, spreadsheet which I have found very useful and easy to get along with. Once you understand the processes of Scrum and what is required the spreadsheet speak a thousand words.\n","title":"Managing Sprints in a Scrum","type":"articles"},{"content":"I have found LINQ to SQL and the Entity Framework has a few missing features, one of these is the ability to update the designer diagrams, and this is where Huagati DBML come to play.\nHuagati DBML/EDMX Tools is an add-in for Visual Studio that adds functionality to the Linq2SQL/DBML diagram designer in Visual Studio 2008, and to the ADO.NET Entity Framework designer in Visual Studio 2008 SP1.\n","date":"26 May 2009","externalUrl":null,"permalink":"/tools-for-linq-to-sql-and-ado-net-entity-framework/","section":"Articles","summary":"I have found LINQ to SQL and the Entity Framework has a few missing features, one of these is the ability to update the designer diagrams, and this is where Huagati DBML come to play.\nHuagati DBML/EDMX Tools is an add-in for Visual Studio that adds functionality to the Linq2SQL/DBML diagram designer in Visual Studio 2008, and to the ADO.NET Entity Framework designer in Visual Studio 2008 SP1.\n","title":"Tools for Linq to SQL and ADO.NET Entity Framework","type":"articles"},{"content":"Updated my extensions on my blog this morning and included a Twitter updater by Miguel Jimenez, TwitterPing.\nHad a few issues with the Extension, but with a few tweeks, and removing the dll by placing the code behind, it means it only needs the .cs file, 🙂\n","date":"24 May 2009","externalUrl":null,"permalink":"/twitterping/","section":"Articles","summary":"Updated my extensions on my blog this morning and included a Twitter updater by Miguel Jimenez, TwitterPing.\nHad a few issues with the Extension, but with a few tweeks, and removing the dll by placing the code behind, it means it only needs the .cs file, ","title":"TwitterPing","type":"articles"},{"content":"Here is a list of Slides and Source code for DDD South West 2009 room 3\nFor full details on each of the talk check out the Agenda These files are now on the DDD South West web site\nHere are some photos too\nhttp://picasaweb.google.co.uk/bryanavery102/DDDWouthWest#\n","date":"24 May 2009","externalUrl":null,"permalink":"/ddd-south-west-presentations-for-room-3/","section":"Articles","summary":"Here is a list of Slides and Source code for DDD South West 2009 room 3\nFor full details on each of the talk check out the Agenda These files are now on the DDD South West web site\n","title":"DDD South West Presentations for Room 3","type":"articles"},{"content":" In object-oriented programming, mock objectsare simulated objects that mimic the behavior of real objects in controlled ways. A computer programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts.\nIt is possible to perform integration testing on the Membership Provider, take a look at this blog entry to find out more Integration testing the MembershipProvider\nWithin the Project we are using Rhino Mocks, Oren Eini is doing a great job with this framework, and I think it’s the only one that seems to be keeping up with the latest features in .NET, other than TypeMock. Plus, it’s totally free to use. It’s also the only one other than TypeMock which does not require you to input strings for method names you’d like to mock, which is cool. It’s compelling to use it but the project is currently maintained by just one person. If Oren decides to drop it, or for any reason stop working on it, the book might turn out outdated quite quickly. Plus, it’s not very widely used, though it seems to be gaining in popularity.\nReferences\nIntroduction to Mocking with Rhino Mocks\nMocking\nCode Samples\n","date":"22 May 2009","externalUrl":null,"permalink":"/mocking/","section":"Articles","summary":" In object-oriented programming, mock objectsare simulated objects that mimic the behavior of real objects in controlled ways. A computer programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to simulate the dynamic behavior of a human in vehicle impacts.\n","title":"Mocking","type":"articles"},{"content":" Calculation Model There are a number of calculations and data transformations that need to take place in order to produce the correct Leakage Calculation.\nIn order to complete the Leakage Calculation as fast as possible we are going to separate the calculations and data transformations in to different processes and control these processes using a Windows Service.\nIn order for a Windows Service to handle separate processes we will be using the Multi Threading abilities of the .NET Framework.\n[edit]Windows Service Installation To install a Windows Service, you could create an installation program that encapsulates the executable for deployment, which I find time consuming and inefficient when testing an application. Or, you could install the service though the InstallUtil.exe process that comes with the .NET Framework.\nI created a simple batch file, install.bat, to simplify installation (and therefore testing) of the service. The batch script is shown below; uninstallation is as simple as creating another batch file, uninstall.bat, with exactly the same script, only substituting the /i (for install) with /u (for uninstall).\n[edit]WCF (Windows Communication Foundation [edit]Introduction We needed to be able to communicate with the Window Service running on the server, from anywhere on the network and the Internet if needed. So the best possible solution was to use [Microsofts WCF], as it is very flexible and configurable.\n[edit]Service Contract We need to implement a service contract, this provides an interface that we can use to be able to communication with the service.\n[edit]Command Provides a method to invoke a command to the service, mainly used for testing and debugging\n[edit]List Get a list of Calculation that are available to be processed\n[edit]Start Start all the calculations\n[edit]StartByName Start a single calculation process by its name\n[edit]Abort Stop all calculations and abort their threads\n[edit]Abort Stop all calculations and abort their threads\n[edit]Status Return if any calculations are still running\n[edit]Activity Display the activity of all the processes that have ever happened since the service started\nThis returns back a String Array, and in each string a comma delimited structure.\nName, Id, Date/Time, Status\n[edit]ActivityById Returns the activity for a given Id\nThis returns back a String Array, and in each string a comma delimited structure.\nName, Id, Date/Time, Status\n[edit]ActivityCancel Clears all the Activity information\n[edit]Multi Threading [edit]Starting Before we start the thread we need to ensure that when the Windows Service is closed, that all the threads are stopped. To do this you must set the thread to a background process withIsBackground\nWhen a thread terminates because of its parent process, it stops dead, and no finally blocks are executed.\nThe same situation arises when a user terminates an unresponsive application via the Windows Task Manager, or a process is killed programmatically via Process.Kill.\nTherefore Restarting the Windows Service will cause the threads to stop in their tracks, which is perhaps what you are after if you restart or stop a service.\n[edit]Abort Abort will work on a thread in almost any state – running, blocked, suspended, or stopped. However if a suspended thread is aborted, a ThreadStateException is thrown – this time on the calling thread – and the abortion doesn’t kick off until the thread is subsequently resumed.\n[edit]Configuration [edit]App.Config The application configuration file can be configured to handle the different calculations, we are using the standard .NET configuration settings, using a Section Group, within the Config Sections tag, of WaterNet, and implementing the leakage section handler, as seen below:\nTo configure the separate calculations you add each calculation in to the leakage tag, as seen below:\nHere is a list of possible configuration options available for the calculation plugins\n[edit]name The name of the Calculation Required\n[edit]assembly_name The assembly name to be used, comprising of the method and the Assembly name, both including the full namespace. Required\n[edit]numberOfThreads sets the maximum number of threads available for this process to run at any one time default = 1\n[edit]isBackground Indicating whether or not a thread is a background thread. default = True\n[edit]priority Indicating the scheduling priority of a thread.\ndefault = Normal\nA thread can be assigned any one of the following priority values:\nHighest\nAboveNormal\nNormal\nBelowNormal\nLowest\n","date":"22 May 2009","externalUrl":null,"permalink":"/rps-calculation-model/","section":"Articles","summary":" Calculation Model There are a number of calculations and data transformations that need to take place in order to produce the correct Leakage Calculation.\n","title":"RPS – Calculation Model","type":"articles"},{"content":"http://samples.syncfusion.com/mvcdemolaunchpad\n","date":"22 May 2009","externalUrl":null,"permalink":"/mvc-tool-case/","section":"Articles","summary":"http://samples.syncfusion.com/mvcdemolaunchpad\n","title":"MVC tool case","type":"articles"},{"content":"Task today is to decide and implement an Continuous Integration build process, I will be looking at two options CruseControl and Team City. The are a lot more but for the purpose of the current .NET environment these are the two I’ll be looking at.\nWhen working in a team, the developer needs to know that any changes he makes and stores in to your repository will work for others. When the developer submits code to the repository they must first update their code to reflect the changes in the repository since they took their copy. The more changes there are to the repository, the more work the developer must do before submitting their own changes.\nEventually, the repository may become so different from the developer’s baseline that they enter what is sometimes called, “integration hell,” where the time it takes to integrate is greater than the time it took to make their original changes. In a worse case scenario, the changes the developer is making may have to be discarded and the work redone.\nContinuous Integration is the practice of integrating early and often, so as to avoid the pitfalls of “integration hell”. The ultimate goal is to reduce timely rework and thus reduce cost and time. When done well, continuous integration has been shown to achieve these goals.\nAfter speaking and Googling for each of the products, I quickly came to the conclusion that although a number of clients I have work with before have been using CruseControl I have found it quite hard to setup and the configuration of XML configuration files can be a bit of a nightmare, and as such we just need a tool to work and not have to maintain. So for the rest of this article I will be focusing on Team City by JetBrains.\nI will be using version 4.5.1. TeamCity-4.5.1.exe (231 mb)\nWhat I like about this product is the licensing, currently the Professional version is free for up to 20 users and 20 build configurations, and when the project get larger you purchase an enterprise license, currently £1,560, ideal way of working and getting you to use the produce.\nIt’s worth watching this short introduction video from Dime Cast, to find out how easy it is to create and use Team City.\nThe Server automates the integration process by monitoring the team’s source control repository directly. Every time a developer commits a new set of modifications, the server will automatically launch an integration build to validate the changes. When the build is complete, the server notifies the developer whether the changes that they committed integrated successfully or not.\nEffectively, integration becomes as easy as checking in code. Using an automated integration server not only makes integration easy, it also guarantees that an integration build will happen. There is no danger of developers forgetting to validate their changes after checking in.\nThe Team City offers several key features:\n• Integration with a variety of Source Control systems\n• Integration with other external tools, such as NAnt and Visual Studio\n• Can build multiple projects on one server\n• Remote management and reporting\nSo down to the installation, once downloaded (231mb file), I installed using all the default settings and it worked, very easy to setup.\nNext was to setup a project, again quite easy, I was attaching to a Visual SourceSafe (VSS) solution, I ran in to my first issue as I was getting directory authentication failed. This was because the running “TeamCity Web Server” was using my System login and it did not have permissions to the network drive for the VSS. A quick change to the TeamCity Build Server service login and it all worked.\nI ran the build on a simple project and it worked without a hitch.\nNext was to install the System Tray Notifier, quite simple, going to the “My Settings \u0026amp; Tools” tab brings a list of download, after a simple download and run, then pointing the HTTP location of the Team City installation, it worked.\nWhat can I say it’s all just too easy to setup.\nPre-tested Commit One issue I had, but not with Team City, is that if you are using MS Test, the built in Visual Studio 2008 testing tool, then you will need to run MS Test. But to run MS Test it is tightly coupled with Visual Studio. Which means to run MS test you’ll need to install a version of Visual Studio on your Continous Intergration machine. Therefore it might be worth using NUnit for testing.\nOne very nice feature of Team City is the ability to perform a Pre-tested Commit, this is possible when you install the Visual Studio Addin\nAn approach which prevents committing defective code into a build, so the entire team’s process is not affected.\nSubmitted code changes first go through testing. If it passes all of the tests, TeamCity can automatically submit the changes to version control. From there, it will automatically be integrated into the next build. If any test fails, the code is not committed, and the submitting developer is notified.\nThe TeamCity plugins for IntelliJ IDEA, Microsoft Visual Studio 2005/2008 and Eclipse extend the respective IDE with the remote run and pre-tested commit features. Developers test their changes by performing a Remote Run. A pre-tested commit is enabled when commit changes if successful option is selected. Reference http://en.wikipedia.org/wiki/Continuous_Integration\nBeyond Continuous Integration: Continuous Monitoring with Owen Rogers\nSetting up CruiseControl.NET to be a Continuous Monitoring Server\nhttp://www.stevetrefethen.com/blog/archives/#Continuous+Integration\nhttp://www.stevetrefethen.com/blog/CCNETBasedEDIInvoicingProjectGoesIntoProduction/\nhttp://sourceforge.net/project/showfiles.php?group_id=71179\u0026amp;package_id=83198\nhttp://ccnetconfig.codeplex.com/\nhttp://ccnetbuildstation.codeplex.com/\n","date":"20 May 2009","externalUrl":null,"permalink":"/continuous-integration/","section":"Articles","summary":"Task today is to decide and implement an Continuous Integration build process, I will be looking at two options CruseControl and Team City. The are a lot more but for the purpose of the current .NET environment these are the two I’ll be looking at.\n","title":"Continuous Integration","type":"articles"},{"content":"http://www.jobserve.com/EC1545A81AE3DF391Z9AED430336436C.jsap\n","date":"20 May 2009","externalUrl":null,"permalink":"/threading/","section":"Articles","summary":"http://www.jobserve.com/EC1545A81AE3DF391Z9AED430336436C.jsap\n","title":"Threading","type":"articles"},{"content":"I came across a little issue today, in that I had an Interface object and I needed to be able to sort the list, I would normally implement the IComparable interface on the concreate type, but I don’t have access to the concreate type in my case.\nI tried several different methods in the end I ended up with using a delegate, and found in SimoneB Blog, which I have extracted the content below:\nSorting a generic List\u0026lt;T\u0026gt; is pretty straightforward if you know how to do it. With C# 2.0, anonymous methods come at hand, as well as the little known Comparison\u0026lt;T\u0026gt; delegate (check out this post for more information about this class as well as other useful classes new to C# 2.0).\nOk, let’s suppose we have a product class (let me save some space by using C# 3.0 syntax).\nclass Product\n{\npublic int ProductID { get; set; }\npublic string ProductName { get; set; }\npublic decimal UnitPrice { get; set; }\n}\nWhen we have a list of products we may want to sort it on the ProductName property before displaying it to the user. This can be accomplished with the Sort method of the List\u0026lt;T\u0026gt; class, which defines several overloads. The most handy in this case is the Sort(Comparison\u0026lt;Product\u0026gt;) method and the result is easily achieved with a couple lines of code.\nList\u0026lt;Product\u0026gt; products = new List\u0026lt;Product\u0026gt;();\nproducts.Sort(delegate(Product p1, Product p2)\n{\nreturn p1.ProductName.CompareTo(p2.ProductName);\n});\nSo far so good, but what if we need to sort our list in several places during the execution of our program? Do we have to write that code each time? Actually no, since we can use the parameterless Sort() method of our list class. What this method does is use the “default comparer” to sort the list. So what’s this default comparer? It’s the comparer that’s automatically created if we implement the IComparable\u0026lt;T\u0026gt; interface. This way we can centralize the sorting logic into our class, and just call the parameterless Sort() method on it whenever we need it sorted on the ProductName property.\npublic class Product : IComparable\u0026lt;Product\u0026gt;\n{\n[…]\npublic int CompareTo(Product other)\n{\nreturn ProductName.CompareTo(other.ProductName);\n}\n}\nOk, now what if we want to be able to sort it on the other two properties, ProductID and UnitPrice? Do we have to write an anonymous method each time as we did in the beginning? Of course no, since there’s a useful trick which prevents us from needing to do that. We can define two static Comparer\u0026lt;Product\u0026gt; properties in our product class, and supply them as parameters to the Sort(Comparer\u0026lt;T\u0026gt;) method of our list whenever we need it sorted on something which is not the default sorting logic.\npublic class Product : IComparable\u0026lt;Product\u0026gt;\n{\n[…]\npublic static Comparison\u0026lt;Product\u0026gt; PriceComparison =\ndelegate(Product p1, Product p2)\n{\nreturn p1.Price.CompareTo(p2.Price);\n};\npublic static Comparison\u0026lt;Product\u0026gt; IDComparison =\ndelegate(Product p1, Product p2)\n{\nreturn p1.ProductID.CompareTo(p2.ProductID);\n};\n[…]\n}\nSince they are static they can be used simply like so: products.Sort(Product.PriceComparison) or products.Sort(Product.IDComparison), which will respectively sort the list by price and id.\nBelow is the full code of the Product class.\npublic class Product : IComparable\u0026lt;Product\u0026gt;\n{\nprivate int id;\nprivate string prodName;\nprivate decimal price;\npublic static Comparison\u0026lt;Product\u0026gt; PriceComparison = delegate(Product p1, Product p2)\n{\nreturn p1.price.CompareTo(p2.price);\n};\npublic static Comparison\u0026lt;Product\u0026gt; IDComparison = delegate(Product p1, Product p2)\n{\nreturn p1.id.CompareTo(p2.id);\n};\npublic int ProductID\n{\nget { return id; }\nset { id = value; }\n}\npublic string ProductName\n{\nget { return prodName; }\nset { prodName = value; }\n}\npublic decimal UnitPrice\n{\nget { return price; }\nset { price = value; }\n}\npublic Product(int id, string prodName, decimal price)\n{\nthis.id = id;\nthis.prodName = prodName;\nthis.price = price;\n}\n#region IComparable\u0026lt;Product\u0026gt; Members\npublic int CompareTo(Product other)\n{\nreturn ProductName.CompareTo(other.ProductName);\n}\n#endregion\npublic override string ToString()\n{\nreturn string.Format(“Id: {0} Name: {1} Price: {2}”, id, prodName, price);\n}\n}\n","date":"19 May 2009","externalUrl":null,"permalink":"/how-to-sort-a-generic-list/","section":"Articles","summary":"I came across a little issue today, in that I had an Interface object and I needed to be able to sort the list, I would normally implement the IComparable interface on the concreate type, but I don’t have access to the concreate type in my case.\n","title":"How to sort a generic List","type":"articles"},{"content":"Been playing around with this hack for some time, it’s fun, I can’t remember where I first got the application from, but I’ve had some harmless fun with it in the office.\nThis small hack allows you to write information to most HP printers LCD screen.\nHPHack.zip (6.49 kb)\n","date":"18 May 2009","externalUrl":null,"permalink":"/well-all-love-a-good-hack/","section":"Articles","summary":"Been playing around with this hack for some time, it’s fun, I can’t remember where I first got the application from, but I’ve had some harmless fun with it in the office.\nThis small hack allows you to write information to most HP printers LCD screen.\n","title":"Well all love a good Hack","type":"articles"},{"content":"I was in need to copying one concreate object to another concreate object, but I needed the flexability that when a new property is added the method would not need to be changed, also I needed the ability for the method to take in any types.\nSo the first take was to generate a method that uses reflections to go over the obecjts properts and set the returning object properties. That was quite simple, then to make the method more flexable I used generics to help with my method, to allow for any types to be used.\nOne thing to note is that you require the try catch, in case the GetValue or SetValue fails, such as if the object is null.\nThis is what I ended up with.\nHere is the VB.NET method\nHere is the C#\n","date":"15 May 2009","externalUrl":null,"permalink":"/copy-one-object-to-another-object/","section":"Articles","summary":"I was in need to copying one concreate object to another concreate object, but I needed the flexability that when a new property is added the method would not need to be changed, also I needed the ability for the method to take in any types.\n","title":"Copy one object to another Object","type":"articles"},{"content":"If you are like me when you are developing you create a Debug version of your application and in turn .NET provides you with .PDB files for debugging, that is as far as I know, want to know more about it then take a look at John Robbins’ Blog on PDB files: what every developer must know\n","date":"14 May 2009","externalUrl":null,"permalink":"/pdb-what-and-why/","section":"Articles","summary":"If you are like me when you are developing you create a Debug version of your application and in turn .NET provides you with .PDB files for debugging, that is as far as I know, want to know more about it then take a look at John Robbins’ Blog on PDB files: what every developer must know\n","title":"PDB, what and why?","type":"articles"},{"content":"If you are like me and you are using DataSets and you need to transfer a table rows collection in to a predefined interface then here is your answer Here is its usage\n","date":"14 May 2009","externalUrl":null,"permalink":"/returning-all-data-from-a-dataset-row/","section":"Articles","summary":"If you are like me and you are using DataSets and you need to transfer a table rows collection in to a predefined interface then here is your answer ","title":"Returning all data from a DataSet Row","type":"articles"},{"content":"I have been on the look out for the ability to display and search a customers database, but having the ability to display millions of records if that what the end users wants. But the trouble is that it can take a long time to return a million records from a data source.\nI’ve talked about paging before in my article LINQ-to-SQL-and-Paging, which works fine for internet based paging, but what about WPF and WinForm Grids, well I came across Vitrual Mode for the Microsoft Data Grid, which can provide an answer. What this allow you to do is, load the data you can see on the screen very quickly and as you scroll through the data is fetched when required.\nBy setting the VirtualMode = true for a data grid, it allows you to add a handler for deail with CellValueNeeded Here is the main body of the code\nEach time the Data grid needs some values it will call the following:\nAnd of course the NameListCache class\nI have attached the source, you will also find a PopulateData project to populate the database with data.\nDataGridViewVirtualModePaging.zip (19.43 kb)\nPopulateData.zip (11.43 kb)\nHere are a few of the database scripts that yu will need for the sample\nNames.sql (581.00 bytes)\nGetNames.sql (786.00 bytes)\n","date":"12 May 2009","externalUrl":null,"permalink":"/only-get-the-data-that-is-needs-to-be-displayed/","section":"Articles","summary":"I have been on the look out for the ability to display and search a customers database, but having the ability to display millions of records if that what the end users wants. But the trouble is that it can take a long time to return a million records from a data source.\n","title":"Only get the data that is needs to be displayed","type":"articles"},{"content":"I’ve had an iPhone for a year and a half now, and I’m still finding things it can do, here are a few things that I have found:\nPressing the Home button twice quickly takes you to your favorites (this can be configured in the setting) Press Home button while pressing the on/off button causes a Print Screen If you continue to home the Home and on/off button it will perform a reboot of your iPhone Have you found any more features that I have missed? ","date":"11 May 2009","externalUrl":null,"permalink":"/hidden-but-found-on-the-iphone/","section":"Articles","summary":"I’ve had an iPhone for a year and a half now, and I’m still finding things it can do, here are a few things that I have found:\nPressing the Home button twice quickly takes you to your favorites (this can be configured in the setting) Press Home button while pressing the on/off button causes a Print Screen If you continue to home the Home and on/off button it will perform a reboot of your iPhone Have you found any more features that I have missed? ","title":"Hidden but found on the iPhone","type":"articles"},{"content":"Stuck with this issue, if needing a ClickOnce installation to display an EULA, I final found a solution, on MSDN\nHere’s a round about way to get your clickonce applications to install with an End user license agreement. Basically you build a redistributable component that can be seen in your prerequsites dialog box under the publish window. This allows a nice way to have all your apps reuse the same agreement, if you want. It’s very easy, you need only to create three files (“eula.txt”, “product.xml”, and “package.xml”) and two folders in this case (“EULApackage”, and “en”). I documented everything below on how I set mine up. it works great. the only thing you’ll have to change is the Name of the component and of course you’ll need your own end user licence agreement saved as eula.txt. The component needs to be put in the following path:\nVisual Studio 2005\nC:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\BootStrapper\\Packages\nVisual Studio 2008\nC:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\Bootstrapper\\Packages\nin this folder you should see some sub folders for other redistributable components. First make a new sub directory for your component. I called mine EULApackage. in this new folder you need the following. -A file called product.xml and a sub folder called “en” (for english) you can do various things with the product.xml file, but here’s the way mine looks\n\u0026lt;?xml version=\"1.0\" encoding=\"utf-8\" ?\u0026gt;\n\u0026lt;Product\nxmlns=\"http://schemas.microsoft.com/developer/2004/01/bootstrapper\"\nProductCode=\"EULA.Bootstrap.Component\"\n\u0026gt;\n\u0026lt;!-- Defines list of files to be copied on build --\u0026gt;\n\u0026lt;PackageFiles\u0026gt;\n\u0026lt;PackageFile Name=\"en/eula.txt\"/\u0026gt;\n\u0026lt;/PackageFiles\u0026gt;\n\u0026lt;Commands\u0026gt;\n\u0026lt;Command PackageFile=\"en/eula.txt\"\nArguments='' \u0026gt;\n\u0026lt;ExitCodes\u0026gt;\n\u0026lt;ExitCode Value=\"0\" Result=\"Success\"/\u0026gt; \u0026lt;DefaultExitCode Result=\"Fail\" FormatMessageFromSystem=\"true\" String=\"GeneralFailure\" /\u0026gt;\n\u0026lt;/ExitCodes\u0026gt;\n\u0026lt;/Command\u0026gt;\n\u0026lt;/Commands\u0026gt;\n\u0026lt;/Product\u0026gt;\n*in this case the file eula.txt was the text file that was my license agreement. Note that it’s not an rtf file. Rtf won’t display propertly using this method.\nNow inside my “en” subfolder i put the eula.txt file and another xml file called package.xml, again this xml file can be used to do all kinds of stuff\nheres the contents of my version*\n\u0026lt;?xml version=\"1.0\" encoding=\"utf-8\" ?\u0026gt;\n\u0026lt;Package\nxmlns=\"http://schemas.microsoft.com/developer/2004/01/bootstrapper\"\nName=\"DisplayName\"\nCulture=\"Culture\"\nLicenseAgreement=\"eula.txt\"\u0026gt;\n\u0026lt;PackageFiles\u0026gt;\n\u0026lt;PackageFile Name=\"eula.txt\"/\u0026gt;\n\u0026lt;/PackageFiles\u0026gt;\n\u0026lt;!-- Defines a localizable string table for error messages and url's --\u0026gt;\n\u0026lt;Strings\u0026gt;\n\u0026lt;String Name=\"DisplayName\"\u0026gt;Companies End User License Agreement\u0026lt;/String\u0026gt;\n\u0026lt;String Name=\"Culture\"\u0026gt;en\u0026lt;/String\u0026gt;\n\u0026lt;String Name=\"CancelFailure\"\u0026gt;User Failed to Accept Companies End User License Agreement.\u0026lt;/String\u0026gt;\n\u0026lt;String Name=\"GeneralFailure\"\u0026gt;A fatal error occurred during the installation of ELUA Component Execution\u0026lt;/String\u0026gt;\n\u0026lt;String Name=\"AdminRequired\"\u0026gt;You do not have the permissions required to install this application. Please contact your administrator.\u0026lt;/String\u0026gt;\n\u0026lt;/Strings\u0026gt; \u0026lt;/Package\u0026gt;\nNote: whatever you put in the DisplayName field is what your user will see when he’s confronted with the eula text If you have all this put together correctly and in the right folders, the next time you start up VS2005 and go to your publish tab -\u0026gt; prerequisites you should see the DisplayName field. Just check this as a prerequisite for you app. when the user clicks install on the publish.htm file it’ll present the user with the conents of your eula.txt file inside of a standard license acceptance dialog box. if the choose accept your stuff installs, if they decline then it exits rather nicely and nothing is installed on their systems. If you mess up the formatting for either of the two files or if you leave out the “en” sub folder then the component won’t show up in the prerequisites dialog (when publishing)\nAdditional notes: although this works great it is a round about method and their are ways around the eula, such as if your publish.htm file allows them to run the application directly (I guess without the bootstrapper starting)but if they click the install button it will run. This also has the benifits of not running every time you publish an update to your clickonce application. They have to run the boot strapper to get the eula to show up (by clicking the install button on publish.htm) I figured out this method by looking at some of the other redistributable components that were already in the path\nVisual Studio 2005\nC:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\BootStrapper\\Packages\nVisual Studio 2008\nC:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\Bootstrapper\\Packages\nYou can look in those other components product.xml and package.xml files to see what cool things they’ve done with them.\nIf you are using Visual Studio 2008, you can also set up your project file to include the Package, here is an example below\n\u0026lt;BootstrapperPackage Include=\"EULA.Bootstrap.Component\"\u0026gt; \u0026lt;Visible\u0026gt;False\u0026lt;/Visible\u0026gt; \u0026lt;ProductName\u0026gt;RPS End User License Agreement\u0026lt;/ProductName\u0026gt; \u0026lt;Install\u0026gt;true\u0026lt;/Install\u0026gt; \u0026lt;/BootstrapperPackage\u0026gt; ","date":"7 May 2009","externalUrl":null,"permalink":"/how-to-get-an-eula-displayed-for-your-clickonce-application/","section":"Articles","summary":"Stuck with this issue, if needing a ClickOnce installation to display an EULA, I final found a solution, on MSDN\nHere’s a round about way to get your clickonce applications to install with an End user license agreement. Basically you build a redistributable component that can be seen in your prerequsites dialog box under the publish window. This allows a nice way to have all your apps reuse the same agreement, if you want. It’s very easy, you need only to create three files (“eula.txt”, “product.xml”, and “package.xml”) and two folders in this case (“EULApackage”, and “en”). I documented everything below on how I set mine up. it works great. the only thing you’ll have to change is the Name of the component and of course you’ll need your own end user licence agreement saved as eula.txt. The component needs to be put in the following path:\n","title":"How to get an EULA displayed for your clickonce application","type":"articles"},{"content":"Creating tests is a very important part of the development cycle, one of the import part of creating tests is to make sure the tests have as little dependencies as possible, this is where Intergration testing comes in to play.\nOne area to Integration test is the Membership Provider and Role Provider, this is quite simple as the interfaces ofr both providers are very well defined.\nI have attached two Integration test Providers, one for the Membership and the other for Roles, So as to keep Visual Basic alive I’ve written this source in VB.NET\nIntegrationTest MembershipProvider.vb (6.24 kb)\nIntegrationTestRoleProvider.vb (4.36 kb)\nOf course the next step would be to Mock these objects\n","date":"7 May 2009","externalUrl":null,"permalink":"/integration-test-using-the-membershipprovider/","section":"Articles","summary":"Creating tests is a very important part of the development cycle, one of the import part of creating tests is to make sure the tests have as little dependencies as possible, this is where Intergration testing comes in to play.\n","title":"Integration Test using the MembershipProvider","type":"articles"},{"content":"Need a quick over view of how MVC can help you, take a look at these series of videos by Bill Burrows, all very simple and easy to follow videos, and what’s more he is running the demos in VB.NET\nThe Model-View-Controller Framework\nDime Casts has a good selection of videos to watch\n","date":"4 May 2009","externalUrl":null,"permalink":"/videos-for-mvc/","section":"Articles","summary":"Need a quick over view of how MVC can help you, take a look at these series of videos by Bill Burrows, all very simple and easy to follow videos, and what’s more he is running the demos in VB.NET\n","title":"Videos for MVC","type":"articles"},{"content":"Okay, I’ve learn’t something new today, so I’d thought I would share it with you, it’s the yeald keyword, the reason why I think I have not used or know about it before is that it is used for an IEnumerable collection, which has come more in to play with LINQ, here is a short example of how it can be used:\nThis generates the following output:\nIt just makes sense to do it this way, much cleaner and much more efficient.\nFor more details check of MSDN on yeald.\nIt’s worth noting that Yield is not support with VB.NET\n","date":"3 May 2009","externalUrl":null,"permalink":"/yeald/","section":"Articles","summary":"Okay, I’ve learn’t something new today, so I’d thought I would share it with you, it’s the yeald keyword, the reason why I think I have not used or know about it before is that it is used for an IEnumerable collection, which has come more in to play with LINQ, here is a short example of how it can be used:\n","title":"Yeald","type":"articles"},{"content":"To understand the the power of MVC you need to understand the Life Cycle, I could go in to great detail about the ASP.NET Lifecycle, but I have found a number of very good articles already providing good amount of information on the LifeCycle. Before going to the pages here is a simple flow diagram of the steps the MVC process goes through\nThe ASP.NET MVC Pipeline – Steve Sanderson\nASP.NET MVC – Living in a Web Forms World\n","date":"3 May 2009","externalUrl":null,"permalink":"/mvc-lifecycle/","section":"Articles","summary":"To understand the the power of MVC you need to understand the Life Cycle, I could go in to great detail about the ASP.NET Lifecycle, but I have found a number of very good articles already providing good amount of information on the LifeCycle. Before going to the pages here is a simple flow diagram of the steps the MVC process goes through\n","title":"MVC LifeCycle","type":"articles"},{"content":"When I am writing an application it is so important to make sure you record and log information correctly, there are a number of free loggers you can use\nLog4Net NLog I have come to use NLog, by Jaroslaw Kowalski, it’s so easy to use and get up and running, which is what you really need if you are using a logger of any type.\nBut what is the best practice when using a log in a live environment?\nOr more importantly what and how do you configure you configuration file to make sure you are logging all your information?\nThe way I see it is, capture your logging to the Event Log and a Database for information and tracing.\nWhen it comes to Errors and Fatal logging then, write it to as many places as you can, an Error file, the Event Log, a Database Log, and perhaps a special Exception Database Log, because if something has failed, you’ll want to shout about it, and you want to record it in as many places as possible.\nHere is an example of an NLog configuration\nNLog.config (2.63 kb)\nTo setup the database use the following creation creation script\nNLogDatabase.sql (1.16 kb)\nMake sure within the SQL Database you have a user “nloguser”, with a password of “nlogpassword”, these are both defined in the NLog configuration file, and can be changed if need be.\nThat is it, all you have to do now is wait for your live application to log some information.\nI am sure there are a few other configuration options available and I welcome anyones comments on how to improve this configuration file.\n","date":"24 April 2009","externalUrl":null,"permalink":"/configuration-for-nlog/","section":"Articles","summary":"When I am writing an application it is so important to make sure you record and log information correctly, there are a number of free loggers you can use\nLog4Net NLog I have come to use NLog, by Jaroslaw Kowalski, it’s so easy to use and get up and running, which is what you really need if you are using a logger of any type.\n","title":"Configuration for NLog","type":"articles"},{"content":"When you need to find if any records exist in a table or a selective snap shot of a table, you are prehaps like me in using the COUNT(*) SQL transaction and see if there are zero counts, but is this the most efficient method?\nAfter a performance issue on one of my applications I found a new extension to LINQ to SQL called ANY(), from Ray Booysen on StackOverflow, here is an example of the SQL that is generated from LINQ:\nThe Results:\nSELECT COUNT(*) AS [value] FROM [dbo].[Employees] AS [t0]\n9\nSELECT (CASE WHEN EXISTS(SELECT NULL AS [EMPTY] FROM [dbo].[Employees] AS [t0]) THEN 1 ELSE 0 END) AS [value]\nTrue\nAs you can see LINQ wins the day again.\n","date":"17 April 2009","externalUrl":null,"permalink":"/finding-if-any-records-exist-in-a-table/","section":"Articles","summary":"When you need to find if any records exist in a table or a selective snap shot of a table, you are prehaps like me in using the COUNT(*) SQL transaction and see if there are zero counts, but is this the most efficient method?\n","title":"Finding if any records exist in a table","type":"articles"},{"content":"Quite often when I start at a new client they ask me what are the benefits of TFS (Team Foundation Server), as they can not justify the cost, as it is very confusing (like may of Microsoft pricing structures)\nI found this about “How much does Team Foundation Server REALLY cost vs SourceSafe?” by Eric Nelson, which is just what I have been looking for, as you can see the cost is not that much more than SourceSafe, and you gain huge benefits from TFS, as it is not just a Source Control, it’s much much more.\n","date":"15 April 2009","externalUrl":null,"permalink":"/tfs-souresafe-or-subversion/","section":"Articles","summary":"Quite often when I start at a new client they ask me what are the benefits of TFS (Team Foundation Server), as they can not justify the cost, as it is very confusing (like may of Microsoft pricing structures)\n","title":"TFS, SoureSafe or Subversion","type":"articles"},{"content":"http://www.hellomorello.com/\nUmbraco\nBlogEngine.NET\n","date":"3 April 2009","externalUrl":null,"permalink":"/cms-options/","section":"Articles","summary":"http://www.hellomorello.com/\nUmbraco\nBlogEngine.NET\n","title":"CMS Options","type":"articles"},{"content":"\nA couple of weeks ago I released an online TV guide for Danish viewers called ifjernsyn.dk. The goal was to make a very simple overview that could easily be accessed from a mobile phone and customized by any visitor without any login. The purpose was to always know what’s on the air right now and what programs will shortly follow – and of course to keep it simple.\nSince the release, some people have asked me about how I did some of the things and one of the most frequently asked questions was how to find movie posters for all the movies. Apparently, people are interested in finding movie posters for their own pet projects involving their own media collection or even a media center plug-in.\nThe code With only the name of a movie, the code will search the Yahoo image search API and return a thumbnail of the poster. The API returns an XML document with both the thumbnail and the full image, so to get the full image you should just change the XPath navigation.\nprivate const string LINK =“http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo\u0026amp;query={0} movie\u0026amp;results=1”;\npublic static string FindMoviePoster(string title)\n{\nstring url = string.Format(LINK, HttpUtility.UrlEncode(title));\nXPathDocument xd = new XPathDocument(url);\nXPathNavigator navigator = xd.CreateNavigator();\nnavigator.MoveToFollowing(XPathNodeType.Element);\nnavigator.MoveToFirstChild();\nnavigator.MoveToFirstChild();\ndo\n{\nif (navigator.LocalName == “Thumbnail”)\n{\nnavigator.MoveToFirstChild();\nreturn navigator.Value;\n}\n} while (navigator.MoveToNext());\nreturn null;\n} The implementation To use the method above in your own web page, simply pass a movie title to the method and the image URL is returned. It could look like this:\nstring posterUrl = FindMoviePoster(“independance day”);;\nif (!string.IsNullOrEmpty(posterUrl))\n{\nimgPoster.ImageUrl = posterUrl;\n}\nThe reason to use the Yahoo API is because it provides the thumbnails as well as the full image.\n","date":"30 March 2009","externalUrl":null,"permalink":"/method-for-retrieving-movie-posters/","section":"Articles","summary":"\nA couple of weeks ago I released an online TV guide for Danish viewers called ifjernsyn.dk. The goal was to make a very simple overview that could easily be accessed from a mobile phone and customized by any visitor without any login. The purpose was to always know what’s on the air right now and what programs will shortly follow – and of course to keep it simple.\n","title":"Method for retrieving movie posters","type":"articles"},{"content":"How may time does it take to lose import files or photos held on your computer before you put in place a backup strategy to protect your files.\nI thought I’d share my personal backup strategy, as I don’t just reply on one process, in fact I have three sync/backup methods\nWindows Live Mesh Carbonite External Hard Drive (Allway Sync) Windows Live Mesh\nThis just has to be the best sync application around, so easy to configure, all you need is a Windows Live Signin and download a small local application and then just select which folders you want to sync.\nOnce you have sync’ed your folders they are available online or anyother machine you have installed Live Mesh application on to.\nWith a built in Remote Desktop application allow you to connect to your pc when you are away from home, this is a god send if you forgot something you left on you machine, or you just need to access one of your applications when you are away from your computer.\nCurrently Live Mesh is in Beta, I think this is due to the fact that it is running on Microsofts Cloud which is not full live yet.\nThe other draw back is it currenly only supports up to 5GB of storage, so you need to pick and choose what you want to sync, but for most users this is more than enough storage space.\nCarbonite\nThis is an online backup storage application, unlike other backup applications it just works and does not get in the way of your working. With unlimitted online storage it is perfect for high end users such as myself. Only limitatation is a maximum file size of 2GB, which is not normal an issue.\nExternal Hard Drive (Allway Sync) With external hard drive so cheap this is a must have, and so easy to setup just purchase, it arrives in the post, plug it i, format and you are away. The final step is to find an application that will sync to the external hard drive. I choose Allway Sync, free download, a little techincal in setting up and getting going, would have been nice if this application had a noddy setup and looked at what and how your machine was configured and prompted you with a possible suggestion for sync. But it’s free and it works.\nSo there you have it, three places where I keep all my files, and two places for my music, photos and videos\nOther Alternatives\nOnline Storage Services Review The Online Storage Gang\n","date":"28 March 2009","externalUrl":null,"permalink":"/backup-strategy/","section":"Articles","summary":"How may time does it take to lose import files or photos held on your computer before you put in place a backup strategy to protect your files.\nI thought I’d share my personal backup strategy, as I don’t just reply on one process, in fact I have three sync/backup methods\n","title":"Backup Strategy","type":"articles"},{"content":"I’ve been looking around for some Data Grid’s and as I love jQuery throught I’d share some Grid written in jQuery, well only one at present, froma Russian developer\nhttp://trirand.com/jqgrid/jqgrid.html\n","date":"28 March 2009","externalUrl":null,"permalink":"/playing-with-datagrids-in-jquery/","section":"Articles","summary":"I’ve been looking around for some Data Grid’s and as I love jQuery throught I’d share some Grid written in jQuery, well only one at present, froma Russian developer\nhttp://trirand.com/jqgrid/jqgrid.html\n","title":"Playing with DataGrids in jQuery","type":"articles"},{"content":"So many places have so many different ideas on what and how things should look, as a developer it is just a cause of accepting what they supply. But from time to time, more often then not, the customer asks to see what you have produced, and even though you may have spent hours or even days getting the code to work correctly, the plain and simple fact is that it look and feels really bad.\nCome on we are developers not designers.\nSo in order to help us developers out it would be good to have a set of images or library images you can look up and use when you needed them?\nWell I came across Tango Desktop Project today, which helps the open source community to ensuring that people like me have access to the right images, even though they might change on the final release, but at least it will get you going and just make your application look great.\nTango Desktop Project\n","date":"27 March 2009","externalUrl":null,"permalink":"/images-and-icons/","section":"Articles","summary":"So many places have so many different ideas on what and how things should look, as a developer it is just a cause of accepting what they supply. But from time to time, more often then not, the customer asks to see what you have produced, and even though you may have spent hours or even days getting the code to work correctly, the plain and simple fact is that it look and feels really bad.\n","title":"Images and Icons","type":"articles"},{"content":"First of you are going to need to download and install SubSonic\nOnce installed just follow the steps below\nWithin Visual Studio\nExternal tools\nTitle “SubSonic DAL”\ncommand sonic.exe\narguments generate /out App_Code\\Generated\nInitial directory $(ProjectDir)\nPrompt for arguments\nuse output window\nscripting Schema and Data You can script out your schema and data (and then version it in your favorite source control system) using SubCommander. Simply use the command “version” and tell SubCommander where to put the data:\nsonic.exe version /out Scripts This will output a script file (.sql) to the local scripts directory of your project\nGenerate a Version of the Database and Data\nTitle Subsonic DB\nCommand Sonic.exe\nArguments version /out App_Code\\DB\nInitial directory $(ProjectDir)\n","date":"26 March 2009","externalUrl":null,"permalink":"/subsonic-autogenerate-database-scripts/","section":"Articles","summary":"First of you are going to need to download and install SubSonic\nOnce installed just follow the steps below\nWithin Visual Studio\nExternal tools\nTitle “SubSonic DAL”\ncommand sonic.exe\narguments generate /out App_Code\\Generated\n","title":"SubSonic Autogenerate Database scripts","type":"articles"},{"content":"If you are like me and you missed your chance to attend Mix09, then all is not lost as you can view the Azure sessions Here’s the list of Azure sessions:\nUsing the Windows Azure Tools for Microsoft Visual Studio to Build Cloud Services Introduction to the Azure Services Platform Overview of Windows Azure Building Web Applications with Windows Azure Windows Azure Storage ","date":"23 March 2009","externalUrl":null,"permalink":"/clouding-computing-at-mix09/","section":"Articles","summary":"If you are like me and you missed your chance to attend Mix09, then all is not lost as you can view the Azure sessions Here’s the list of Azure sessions:\nUsing the Windows Azure Tools for Microsoft Visual Studio to Build Cloud Services Introduction to the Azure Services Platform Overview of Windows Azure Building Web Applications with Windows Azure Windows Azure Storage ","title":"Clouding Computing at Mix09","type":"articles"},{"content":"Updates to the Azure platform, must spend some time on this soon\nGreetings from the Azure Services Platform Team,\nWe are excited to announce that we have released an update to the Windows® Azure™ SDK and Windows Azure Tools for Microsoft Visual Studio®. These latest releases are available here:\nInstall both the Windows Azure Tools for Visual Studio and SDK: http://go.microsoft.com/fwlink/?LinkId=128752 Install the Windows Azure SDK alone: http://go.microsoft.com/fwlink/?LinkId=130232 What’s new in Windows Azure SDK\nSupport for developing Managed Full Trust applications. It also provides support for Native Code via PInvokes and spawning native processes. Support for developing FastCGI applications, including support for rewrite rules via URL Rewrite Module. Improved support for the integration of development storage with Visual Studio, including enhanced performance and support for SQL Server (only local instance). What’s new in Windows Azure Tools for Microsoft Visual Studio\nCombined installer includes the Windows Azure SDK Addressed top customer bugs Native Code Debugging Update Notification of future releases FastCGI template We will continue to release updates to Windows Azure and its tools based on your feedback. Please visit http://go.microsoft.com/fwlink/?LinkId=130231 to share your Windows Azure experiences.\nThank you for your continued interest.\nSincerely,\nAzure Services Platform Team\n","date":"19 March 2009","externalUrl":null,"permalink":"/updated-windows-azure-sdks/","section":"Articles","summary":"Updates to the Azure platform, must spend some time on this soon\nGreetings from the Azure Services Platform Team,\nWe are excited to announce that we have released an update to the Windows® Azure™ SDK and Windows Azure Tools for Microsoft Visual Studio®. These latest releases are available here:\n","title":"Updated Windows Azure SDKs","type":"articles"},{"content":"Now that MVC has been released, it’s worth getting hold of a free MVC book, which should help you get going on using MVC.\naspnetmvc-nerdinner_v1.pdf (13.78 mb)\nhttp://nerddinner.codeplex.com/\n","date":"18 March 2009","externalUrl":null,"permalink":"/free-asp-net-mvc-ebook-nerddinner-com-walkthrough/","section":"Articles","summary":"Now that MVC has been released, it’s worth getting hold of a free MVC book, which should help you get going on using MVC.\naspnetmvc-nerdinner_v1.pdf (13.78 mb)\nhttp://nerddinner.codeplex.com/\n","title":"Free ASP.NET MVC eBook – NerdDinner.com Walkthrough","type":"articles"},{"content":"Finally Microsoft have released MVC…\nASP.NET MVC 1.0 provides a new Model-View-Controller (MVC) framework on top of the existing ASP.NET 3.5 runtime. This means that developers can take advantage of the MVC design patterns to create their Web Applications which includes the ability to achieve and maintain a clear separation of concerns (the UI or view from the business and application logic and backend data), as well as facilitate test driven development (TDD). The ASP.NET MVC framework defines a specific pattern to the Web Application folder structure and provides a controller base-class to handle and process requests for “actions”. Developers can take advantage of the specific Visual Studio 2008 MVC templates within this release to create their Web applications, which includes the ability to select a specific Unit Test structure to accompany their Web Application development.\nThe MVC framework is fully extensible at all points, allowing developers to create sophisticated structures that meet their needs, including for example Dependency Injection (DI) techniques, new view rendering engines or specialized controllers.\nAs the ASP.NET MVC framework is built on ASP.NET 3.5, developers can take advantage of many existing ASP.NET 3.5 features, such as localization, authorization, Profile etc.\nIf you have not already done so, check out Steve Sanderson‘s book on MVC, ","date":"18 March 2009","externalUrl":null,"permalink":"/mvc-has-been-released/","section":"Articles","summary":"Finally Microsoft have released MVC…\nASP.NET MVC 1.0 provides a new Model-View-Controller (MVC) framework on top of the existing ASP.NET 3.5 runtime. This means that developers can take advantage of the MVC design patterns to create their Web Applications which includes the ability to achieve and maintain a clear separation of concerns (the UI or view from the business and application logic and backend data), as well as facilitate test driven development (TDD). The ASP.NET MVC framework defines a specific pattern to the Web Application folder structure and provides a controller base-class to handle and process requests for “actions”. Developers can take advantage of the specific Visual Studio 2008 MVC templates within this release to create their Web applications, which includes the ability to select a specific Unit Test structure to accompany their Web Application development.\n","title":"MVC has been released","type":"articles"},{"content":"What with the release of LINQ to Entities, and LINQ to SQL, which one performs better?\nFor comparison of performance it is worth chekcing out Eric’s blog, but I still perfer LINQ to SQL.\nNot that I would use the Entity Framework yet, see my article on this\n","date":"17 March 2009","externalUrl":null,"permalink":"/speed-and-performance-linq-to-sql-or-linq-to-entities/","section":"Articles","summary":"What with the release of LINQ to Entities, and LINQ to SQL, which one performs better?\nFor comparison of performance it is worth chekcing out Eric’s blog, but I still perfer LINQ to SQL.\nNot that I would use the Entity Framework yet, see my article on this\n","title":"Speed and Performance LINQ to SQL or LINQ to Entities","type":"articles"},{"content":"Threading in C# by Joseph Albahari\n","date":"16 March 2009","externalUrl":null,"permalink":"/multi-threading-in-net/","section":"Articles","summary":"Threading in C# by Joseph Albahari\n","title":"Multi Threading in .NET","type":"articles"},{"content":" Arrive on Friday night, preferably at city airport and head east to Brick lane for a curry. After dinner have drinks at the Vibe bar or 93 feet east. If you are feeling super energetic see what is going on at Sosho, Cargo or Electricity showrooms before getting a good night of sleep.\nSaturday morning, get up early and have breakfast at Patisserie Valerie in Knightsbridge. Have a wander around Harrods for an hour or two making sure that you check out the food hall. Jump on the tube and head over to Camden. You may enjoy the market – I don’t – but if the chaos isn’t for you get off at Chalk Farm station rather than Camden to avoid it all. Grab lunch at Thanh Binh one of the best cheap Vietnamese restaurants in London, I recommend the Pho.\nAfter lunch, walk to the top of Primrose hill for one of the best views of the whole city. On the way back to the tube, stop for a pint or two outside The engineer or The queens.\nI’d suggest a rest at this point so you can make the most of your evening. For dinner book Latium and have cocktails before/after at the Sanderson.\nYou are on your own for the evening. I don’t really do clubbing any more, but the one piece of advice I give is don’t just wander to Leicester square and choose a venue, there are some absolute hovels. If you are just after a few more drinks after dinner I like the bar at the Charlotte street hotel.\nSunday morning, make sure you enjoy a full English breakfast to start your day. Your hotel probably serves one and to be honest there isn’t any particular culinary skill involved in making one so it is hardly worth hunting down an ‘authentic greasy spoon’ cafe.\nGet a tube to Westminster and walk over the bridge enjoying the uber tourist views of Big ben and the houses of parliament. Get a boat from Waterloo pier next to the London eye to Bankside pier, browse Tate modern for a while then cross the river using the millennium foot bridge, head up to St. Pauls Cathedral and check out thewhispering gallery.\nMake sure you use the Thames Clippers commuter boats. The tourist boats are over priced and very slow.\nBack on the boat to Greenwich, from Blackfriars pier. Walk through the grounds of the naval college and into the park, up to the observatory for another view over London. If you have time check out the three markets in Greenwich.\nFinish your trip with a late Sunday roast and a beer at the Plume of feathers (you’ll need to book a sitting at 2 or 4pm). Get on the DLR and head back to city airport!\nThat is just one of many ways of spending a weekend in London. I missed out Fish and Chips, some great markets and many of my favourite pubs simply because of time constraints. I also tried to leave plenty of spare time between my recommendations so you can wander off the beaten track and discover your own London – in my experience, just wandering is one of the true joys of travel.\nMy final tip, here is what to avoid. Leicester Square, Theatre Land, The London eye, Buckingham palace. Some Londoners may passionately disagree, but I think you’d be wasting valuable time.\nSo, if you are reading this and thinking of visiting, enjoy my city. Arguably the greatest on earth.\n","date":"16 March 2009","externalUrl":null,"permalink":"/london/","section":"Articles","summary":" Arrive on Friday night, preferably at city airport and head east to Brick lane for a curry. After dinner have drinks at the Vibe bar or 93 feet east. If you are feeling super energetic see what is going on at Sosho, Cargo or Electricity showrooms before getting a good night of sleep.\n","title":"London","type":"articles"},{"content":"umbraco – open-source .Net CMS\nWikiBook\nForum for Umbraco\n","date":"16 March 2009","externalUrl":null,"permalink":"/umbraco/","section":"Articles","summary":"umbraco – open-source .Net CMS\nWikiBook\nForum for Umbraco\n","title":"Umbraco","type":"articles"},{"content":"After looking around and playing with WCF for a while, it had come to my notice that all the examples that I could find were over complex, then I came across Ralf’s Sudelbücher blog entry for “A truely simple example to get started with WCF“, so simple, so to help you along here is the C# source code that I have written, with a few additions in that the solution also has a client console that calls the WCF application to show a true sence of what is happening.\nSimpleWCF.zip (21.68 kb)\n","date":"11 March 2009","externalUrl":null,"permalink":"/creating-a-simple-wcf-application/","section":"Articles","summary":"After looking around and playing with WCF for a while, it had come to my notice that all the examples that I could find were over complex, then I came across Ralf’s Sudelbücher blog entry for “A truely simple example to get started with WCF“, so simple, so to help you along here is the C# source code that I have written, with a few additions in that the solution also has a client console that calls the WCF application to show a true sence of what is happening.\n","title":"Creating a Simple WCF application","type":"articles"},{"content":"The BBC have updated the mobile access for the website, it is a much improved access point, and works very well on my iPhone\nhttp://www.bbc.co.uk/mobile/betahome\n","date":"11 March 2009","externalUrl":null,"permalink":"/bbc-mobile-greatly-improved/","section":"Articles","summary":"The BBC have updated the mobile access for the website, it is a much improved access point, and works very well on my iPhone\nhttp://www.bbc.co.uk/mobile/betahome\n","title":"BBC Mobile greatly improved","type":"articles"},{"content":"I like this ad, it says so much about our world today\n","date":"10 March 2009","externalUrl":null,"permalink":"/avatar-which-one-are-you/","section":"Articles","summary":"I like this ad, it says so much about our world today\n","title":"Avatar – Which one are you?","type":"articles"},{"content":"Okay, where has the Activity Monitor gone in Microsoft SQL Server Management Studio 2008?\nOpen Microsoft SQL Server Management Studio. In Object Explorer, right click on the server and select Activity Monitor. Please note that the Activity Monitor is not available in the context menu unless you select the server. You cannot launch the Activity Monitor when you select a database, another folder, etc. Why did Microsoft move this, I don’t know\n","date":"10 March 2009","externalUrl":null,"permalink":"/sql-2008-activity-monitor/","section":"Articles","summary":"Okay, where has the Activity Monitor gone in Microsoft SQL Server Management Studio 2008?\nOpen Microsoft SQL Server Management Studio. In Object Explorer, right click on the server and select Activity Monitor. Please note that the Activity Monitor is not available in the context menu unless you select the server. You cannot launch the Activity Monitor when you select a database, another folder, etc. Why did Microsoft move this, I don’t know\n","title":"SQL 2008 Activity Monitor","type":"articles"},{"content":"Working hard with VB.Net, hard work, as I find C# much cleaner, but VB.NET does have the advantage of be able to edit code while debugging. And it compiles while you are working, but I have found that with 64 projects in my solution that the automatic compiler sometimes, quite a lot of the times hogs the machines resources, it would be nice to be able to turn the auto compiler off.\n","date":"10 March 2009","externalUrl":null,"permalink":"/visual-basic-auto-compiler/","section":"Articles","summary":"Working hard with VB.Net, hard work, as I find C# much cleaner, but VB.NET does have the advantage of be able to edit code while debugging. And it compiles while you are working, but I have found that with 64 projects in my solution that the automatic compiler sometimes, quite a lot of the times hogs the machines resources, it would be nice to be able to turn the auto compiler off.\n","title":"Visual Basic auto compiler","type":"articles"},{"content":"There comes a time when you are using LINQ to SQL that you just have to find out what SQL is being generated, for what ever reason that is, here a a few ways to get the SQL you are looking for:\nYou can use SQL Server Profile to see the traffic going to and from the database\nBut if you are like me you want more control over your processes, so you can use the DataContext.Log, and output the log to a window, or in the case below the console window\nOne last method is to just write out an objects SQL, using the GetCommand, as seen below\n","date":"6 March 2009","externalUrl":null,"permalink":"/viewing-the-sql-that-is-generated-from-linq-to-sql/","section":"Articles","summary":"There comes a time when you are using LINQ to SQL that you just have to find out what SQL is being generated, for what ever reason that is, here a a few ways to get the SQL you are looking for:\n","title":"Viewing the SQL that is generated from LINQ to SQL","type":"articles"},{"content":"I need to generate a Windows Service application, I’ve done this before, but could I remember how to do it. In my searching I found this code sample very useful Creating a Basic Windows Service in C# on The Code Project\nWindowsService_Src\nAnother useful article I found was from Microsoft Windows Services: New Base Classes in .NET Make Writing a Windows Service Easy\n","date":"3 March 2009","externalUrl":null,"permalink":"/windows-service/","section":"Articles","summary":"I need to generate a Windows Service application, I’ve done this before, but could I remember how to do it. In my searching I found this code sample very useful Creating a Basic Windows Service in C# on The Code Project\n","title":"Windows Service","type":"articles"},{"content":"\nGo! Quickly! Stop reading this and register now! Registration for DDD South West is now open. Be able to tell your grandchildren that you were there at the very beginning. Remember, there can be only one first time.\nDDD South West is a free one day technical event on Saturday 23rd May 2009 at Queens College, Taunton with 13 of the countries’ best speakers providing 19 technical presentations.\n","date":"3 March 2009","externalUrl":null,"permalink":"/ddd-south-west-registration-is-open/","section":"Articles","summary":"\nGo! Quickly! Stop reading this and register now! Registration for DDD South West is now open. Be able to tell your grandchildren that you were there at the very beginning. Remember, there can be only one first time.\n","title":"DDD South West Registration Is Open!","type":"articles"},{"content":"Just found a great LINQ tool for quering any database LINQPad, is so useful I almost fell off my chair when I found it.\nIf you’re using LINQ then this is a must on a list of tool you need to have.\nWhen I was using it I thought it would be nice to have Autocompletion, and it does, so long as you register the product.\n","date":"27 February 2009","externalUrl":null,"permalink":"/bye-bye-sql-enterprise-manager/","section":"Articles","summary":"Just found a great LINQ tool for quering any database LINQPad, is so useful I almost fell off my chair when I found it.\nIf you’re using LINQ then this is a must on a list of tool you need to have.\n","title":"Bye Bye SQL Enterprise Manager","type":"articles"},{"content":"If you are like me, when you have generated your website you’ll need to make sure it works in all the Web Browsers.\nMy normal approach would be to fire up all my different Virtual Machines, each with a virgin copy of each web browser. This process works fine and it is a very good way of making sure all your site works in different browsers.\nHowever I came across a site today, Browser Shots, with thanks to Guy, that will run your website in a host of different browsers, and return back a screen shot of what it looks like, this is the fastest way to see if your site works in a lot of Browsers. Just enter your website and let it do all the work for you.\n","date":"25 February 2009","externalUrl":null,"permalink":"/testing-your-website-with-different-browsers/","section":"Articles","summary":"If you are like me, when you have generated your website you’ll need to make sure it works in all the Web Browsers.\nMy normal approach would be to fire up all my different Virtual Machines, each with a virgin copy of each web browser. This process works fine and it is a very good way of making sure all your site works in different browsers.\n","title":"Testing your Website with different browsers","type":"articles"},{"content":"The problem is you have a number of PlugIns in your application, however how do you know which plugins have implemented an interface for a task you need to perform?\nFollowing on from my last article, Plugin Model, I will create a new interface, implement that interface and then find the Plugin that implments that interface.\nFirst lets create a simple Interface\nNext implement the interface to a plugin controller class\nYou can see it here as HelloWorld()\nOkay now we need to find which plugins inplement that interface\nAs you can see above we go over the collection of plugins and check to see if the plugs has a TypeOf IInterface1, if it does then the plugin supports that interface. So we can now convert the plugin in to the Interface type and use its interfaces.\nI then took this a little further and implemented a Generic method that gets a list of support objects that support a given interface\n","date":"13 February 2009","externalUrl":null,"permalink":"/how-to-determine-is-a-plugin-implements-an-interface/","section":"Articles","summary":"The problem is you have a number of PlugIns in your application, however how do you know which plugins have implemented an interface for a task you need to perform?\nFollowing on from my last article, Plugin Model, I will create a new interface, implement that interface and then find the Plugin that implments that interface.\n","title":"How to determine is a Plugin implements an interface","type":"articles"},{"content":"I’ve been working with a Plugin model for a few weeks now and I thought it was time I should document the model.\nTask is to build an application that you can plugin models via the .config file, and provide a level of configuration for each plugin via the .config file.\nThis example is for the purposes of example and you should perform more checks to perform validation to ensure that the application is more rebust. Oh, and you can now do all of this using IoC containers, which I may cover another day. But I have found serious issues with IoC containers and VB.NET, as VB.NET does not support implicit interface implementation whereas C# does, but that is another issue for another day.\nFirst lets create the interfaces that will be required for a Plugin to work\nThe PlugInName and Version are just so we can hold general information about the Plugins.\nThe Initialise method will be called to start the plugin up and when you are finished you must call the Finalise method.\nI have included InstalledPlugInElement, which will hold all the configuration information for the plugin that can be stored in the .config file.\nLets have a quick look at the InstalledPlugInElement class\nHere are hold the assembly name and a configuration parameter for to enable the Cache for the plugin\nNext we need to handle the .config file and the section where the plugs are to be configured, this will be held in the InstalledPlugInSectionHandler, this inherits the ConfigurationSection, as seen below\nOkay that’s it for now with what we need for the plugins, next we need to be able to load the plugins, with the help of a PlugInLoader\nOkay this is quite a lot of code for one method.\nWhat we are going to do in this method is get a list of plugins that are supplied in the .config file, and when we create a new instance of the plugin we’ll pass in the Installed plugin Elements that are in the .config file.\nThe section of the .config that holds the plugin information is “plug_ins”, and we get a list of said plugins from the .config file.\nYou will also require InstalledPlugInCollection, which you’ll find in the source at the bottom of this article.\nThe PlugIn\nOf now lets create our PlugIn, generate a new project and add a controller class\nOf course this controller class implments the IPlugIn interface we created earlier.\nWe set the Plugin Name and Version number.\nWhat you will also see is we can set the Cache Enabled, which is pulled in from the .config file\nNow we can load the plugins in to a collection of plugins\nThat’s it for plugins, in another article I will go over how the determine if a plugin implements an interface that you may wish to use.\nPlugInExample.zip (42.28 kb)\n","date":"13 February 2009","externalUrl":null,"permalink":"/plugin-model/","section":"Articles","summary":"I’ve been working with a Plugin model for a few weeks now and I thought it was time I should document the model.\nTask is to build an application that you can plugin models via the .config file, and provide a level of configuration for each plugin via the .config file.\n","title":"Plugin Model","type":"articles"},{"content":"Here is a list of best kept secrets that developers keep under their hats for looking in to what your Windows system is doing:\nsvchost Viewer – A program to see what all those svchost.exe are running.\nAutoHotKey\nLaunchy\nNotepad2\nGhostDoc – Make those comments and documenting classes, methods and properties so much easier\nSysInternals ProcMonitor\nPaint.Net – it goes without saying, probably the best free image editor around\nUnlocker – Got a file locked, free that lock TestDriven.Net\nMSBuild Extension Pack – If you are building a Continuous Integration server, you are going to have to have these tools\nPortable Apps – A must when you are working on clients site, means you have all the tools on your portable drive that you can load without the need to install anything on the clients machine\n","date":"12 February 2009","externalUrl":null,"permalink":"/collection-of-tools/","section":"Articles","summary":"Here is a list of best kept secrets that developers keep under their hats for looking in to what your Windows system is doing:\nsvchost Viewer – A program to see what all those svchost.exe are running.\n","title":"Collection of Tools","type":"articles"},{"content":"Finally found a link to enable you to be able to use Google fully on your iPhone\nhttp://www.google.com/support/mobile/bin/topic.py?topic=13587\n","date":"10 February 2009","externalUrl":null,"permalink":"/iphone-and-google/","section":"Articles","summary":"Finally found a link to enable you to be able to use Google fully on your iPhone\nhttp://www.google.com/support/mobile/bin/topic.py?topic=13587\n","title":"iPhone and Google","type":"articles"},{"content":"I’ve been having a play with Picasa API, and come up with this Extension for BlogEngine.\nAll you have to do is pake the picture.cs file and place it in “\\App_Code\\Extensions” folder, and it takes care of everything for you.\nPicture.zip (1.92 kb)\nHow it works\nFirst the extension will use the admin email address and then add all the newletter e-mail address to a user list, then check with Picasa to see if they have an account. The extension then has a list of user with valid Picasa Albums.\nWhen you open an article the extension will go over all the Tags and see if any of the Picasa Albums in your user list has the same tags, if it does then the photos will be added to the article.\nI do Cache the objects, so once the initial load of the article has taken place it is stored in Cache, as it can take some time to compile the list of photos depending how many active user Picasa Albums you have.\nOne enhancement I would like to include is for the loading of the photos to happen behind the scenes and show a wait icon while the extension goes and gets the photos from Picasa. But I’m not sure how to do this in an Extension, if you know please let me know too.\nI’ve got it working on my Village Website\nhttp://www.bromham.org.uk/\n","date":"8 February 2009","externalUrl":null,"permalink":"/picasa-photos-in-your-blogengine-site/","section":"Articles","summary":"I’ve been having a play with Picasa API, and come up with this Extension for BlogEngine.\nAll you have to do is pake the picture.cs file and place it in “\\App_Code\\Extensions” folder, and it takes care of everything for you.\n","title":"Picasa photos in your BlogEngine site","type":"articles"},{"content":"Okay you are developing a WinForm application and you are looking at performance, one area is Caching of information, but wait a minute I’ve been using caching in my web applications for sometime, but how do you do it from a WinForm application as you don’t have a host to store your cache.\nWould you know it you can use the web cache too, just you have to take a few extra steps to retain your cache, either in memory or in temporary files.\nYou can use the HttpRequest to store the System.Web.Cache objects in your application, and this works well.\nI also came across any Blog, providing another method to Caching, however I have a little concern over this method of caching in files as you are likely to get file locking.\nUsing System.Web.Caching From The Console Or Windows Forms\nI’ve written my own simple VB.NET application to show it working and just holding the Cache in memory for the life of the application.\nWinFormCache.zip (17.73 kb)\nOf course you could run a Windows Service which holds all the Cache information, this way it will be available to all your WinForm applications should you require it.\n","date":"6 February 2009","externalUrl":null,"permalink":"/caching-from-a-non-web-applications/","section":"Articles","summary":"Okay you are developing a WinForm application and you are looking at performance, one area is Caching of information, but wait a minute I’ve been using caching in my web applications for sometime, but how do you do it from a WinForm application as you don’t have a host to store your cache.\n","title":"Caching from a non Web applications","type":"articles"},{"content":"\n“Dilbert” on Extreme and Agile Programming\n","date":"5 February 2009","externalUrl":null,"permalink":"/dilbert-on-extreme-and-agile-programming/","section":"Articles","summary":"\n“Dilbert” on Extreme and Agile Programming\n","title":"“Dilbert” on Extreme and Agile Programming","type":"articles"},{"content":"Found a nice post from Chris Blankenship’s blog about generating a Random Password, the code is just one line of code and is quite simple\nstring password = Membership.GeneratePassword(12, 1); Console.Writeline(“Random Password: ” + password);\n","date":"4 February 2009","externalUrl":null,"permalink":"/generating-a-random-password/","section":"Articles","summary":"Found a nice post from Chris Blankenship’s blog about generating a Random Password, the code is just one line of code and is quite simple\nstring password = Membership.GeneratePassword(12, 1); Console.Writeline(“Random Password: ” + password);\n","title":"Generating a Random Password","type":"articles"},{"content":"I’ve come across two issues with the Entity Framework, one that effects any language and one just for VB.NET\nIt’s quite simple, the Entity Framework generates edmx files, however that Inherits Global.System.Data.Objects.DataClasses.EntityObject, which means when you create your Partial class you can not Inherit from your own base class.\nThe second issue is related to VB.NET, as if you are intending to use Dependence Injection or IoC you need to have an Interface defined and to implement an Interface in VB.NET you must add Implements after each Property and Method, which you can not do as the framework generates it’s own code.\nI’ve attached both C# and VB.NET examples, none of which compile\nEntity Framework Issues.zip (42.58 kb)\n","date":"4 February 2009","externalUrl":null,"permalink":"/entity-framework-issues/","section":"Articles","summary":"I’ve come across two issues with the Entity Framework, one that effects any language and one just for VB.NET\nIt’s quite simple, the Entity Framework generates edmx files, however that Inherits Global.System.Data.Objects.DataClasses.EntityObject, which means when you create your Partial class you can not Inherit from your own base class.\n","title":"Entity Framework Issues","type":"articles"},{"content":"Why can I never seem to remember the name of software I have used before? Perhaps that is one reason why I try to keep my blog up to date, as I use it as a brain dump of tasks I have been working on, so when my memory fails me I can also revert to my Blog and perform a search or look at the archive and find what I as working on say 2 years ago. I know softare moves on, but I always find some software no matter how old it is, just can’t be beaten.\nOne piece of software that I always go back to is Fiddler, HTTP Debugging Proxy which logs all HTTP traffic between your computer and the Internet. Fiddler allows you to inspect all HTTP Traffic, set breakpoints, and “fiddle” with incoming or outgoing data. Fiddler includes a powerful event-based scripting subsystem, and can be extended using any .NET language.\nOf course if you are using Visual Studio and the in built web server, which works without going through the Proxy, at it is running locally.\nIE7 and the .NET Framework are hardcoded not to send requests for Localhost through any proxies, and as a proxy, Fiddler will not receive such traffic. Here is a snippet from fiddler web site which works very well.\nThe workaround is to use your machine name as the hostname instead of Localhost or 127.0.0.1. So, for instance, rather than hitting http://localhost:8081/mytestpage/, instead visit http://machinename:8081/mytestpage/. …Or, if you’re using Fiddler v2.1.8 or later, just use http://ipv4.fiddler to hit localhost on the IPv4 adapter, or use http://ipv6.fiddler to hit localhost on the IPv6 adapter. This works especially well with the Visual Studio test webserver (codename: Cassini) because the test server only listens on the IPv4 loopback adapter.\nLastly, you could Customize your Rules file like so:\nstatic function OnBeforeRequest(oSession:Fiddler.Session){\nif (oSession.HostnameIs(“MYAPP”)) { oSession.host = “127.0.0.1:8081”; }\n}\n…and then just hit http://myapp, which will act as an alias for 127.0.0.1:8081.\n","date":"1 February 2009","externalUrl":null,"permalink":"/http-sniffer/","section":"Articles","summary":"Why can I never seem to remember the name of software I have used before? Perhaps that is one reason why I try to keep my blog up to date, as I use it as a brain dump of tasks I have been working on, so when my memory fails me I can also revert to my Blog and perform a search or look at the archive and find what I as working on say 2 years ago. I know softare moves on, but I always find some software no matter how old it is, just can’t be beaten.\n","title":"HTTP Sniffer","type":"articles"},{"content":"I’ve always wanted to hook in to Goolges Picasa Web Album to allow for sites to store and display photos from Picasa, and I have just found a great blog from Richard Nilsson on the startings of building a photo album on your site, well worth a visit.\nGoogle also has a Picasa Web Albums Data API for .NET, so what ae we waiting for?\n","date":"31 January 2009","externalUrl":null,"permalink":"/picasa-googles-web-album/","section":"Articles","summary":"I’ve always wanted to hook in to Goolges Picasa Web Album to allow for sites to store and display photos from Picasa, and I have just found a great blog from Richard Nilsson on the startings of building a photo album on your site, well worth a visit.\n","title":"Picasa Google’s web album","type":"articles"},{"content":"I’ve been using Anonymous methods and Lambdas extressions for a little while now, but I do find as I go from customer to customer, do they really understand what all this means?\nI can now safely say that Mike Taulty has posted a very good blog on the subject, which should assist in helping people to understand what it is all about.\nAnother useful link is from Devx From Delegate to Lambda\n","date":"29 January 2009","externalUrl":null,"permalink":"/anonymous-methods-lambdas-confusion/","section":"Articles","summary":"I’ve been using Anonymous methods and Lambdas extressions for a little while now, but I do find as I go from customer to customer, do they really understand what all this means?\nI can now safely say that Mike Taulty has posted a very good blog on the subject, which should assist in helping people to understand what it is all about.\n","title":"Anonymous methods, Lambdas, Confusion","type":"articles"},{"content":"Microsoft have release MVC Release Candidate 1, I’ve had a little play with MVC and it looks very promising, although it is a different way of programming for your web site, the benefits are huge.\nYou can download MVC Release Candidate 1 from this link\nI’m personally going to wait for our usergroup member to publish his book before I take a leap in to the MVC world.\n","date":"28 January 2009","externalUrl":null,"permalink":"/mvc-release-candidate-1/","section":"Articles","summary":"Microsoft have release MVC Release Candidate 1, I’ve had a little play with MVC and it looks very promising, although it is a different way of programming for your web site, the benefits are huge.\nYou can download MVC Release Candidate 1 from this link\n","title":"MVC Release Candidate 1","type":"articles"},{"content":"I’m selling my Ski Boots on Ebay, if any one is interested\nhttp://cgi.ebay.co.uk/ws/eBayISAPI.dll?ViewItem\u0026amp;item=300289215769\n","date":"25 January 2009","externalUrl":null,"permalink":"/ski-boots-for-sale/","section":"Articles","summary":"I’m selling my Ski Boots on Ebay, if any one is interested\nhttp://cgi.ebay.co.uk/ws/eBayISAPI.dll?ViewItem\u0026item=300289215769\n","title":"Ski Boots for sale","type":"articles"},{"content":"I’m not currently working on WCF, but I when I find some useful links I’ll add them here\nSet of links for WCF\nGetting Started with Windows Communication Foundation (WCF)\nIf you’re going to do any extensive WCF services it is worth getting hold of Programming WCF Services by Juval Lowy\n","date":"24 January 2009","externalUrl":null,"permalink":"/wcf-getting-started/","section":"Articles","summary":"I’m not currently working on WCF, but I when I find some useful links I’ll add them here\nSet of links for WCF\nGetting Started with Windows Communication Foundation (WCF)\nIf you’re going to do any extensive WCF services it is worth getting hold of Programming WCF Services by Juval Lowy\n","title":"WCF getting started","type":"articles"},{"content":"I’ve been playing with my Weather station, Watson W-8681, since Christmas Day, and I love it.\nIt came in a small box, all tidy and wanting to be built on Christmas day\nTaking it all out of the box, you get the rain water measurer, wind direction, software CD, temp and wireless sensor and a cover to protect it, wind speed and all the fixing clamps needed.\nThe LCD display is very clear, and it is wireless, which means I can place it anywhere in the house and still know what is happening outside. A single click anywhere on the LCD display lights up the panel for easy viewing.\nOnce the instruments are all assembled, it looks like a real weather station.\nSoftware need to run the weather station, and pick up the data, which then stores all the data in EasyWeather.dat file\nEasy Weather v4.ZIP (1.36 mb)\nTo enable upload to the Internet I used Cumulus software which take the EasyWeather.dat file and processes it, uploading html file via FTP and it also allow you to upload the data to Weather Underground, to allow others to see your results\nCumulusSetup.exe (2.10 mb)\nI have all my data being sent to the village web site All in all I am very pleased with the Weather Station. The software is very retro and could do with being update, perhaps to WPF or Silverlight, but I don’t have the time at the moment to embark on a new project.\n","date":"24 January 2009","externalUrl":null,"permalink":"/my-weather-station/","section":"Articles","summary":"I’ve been playing with my Weather station, Watson W-8681, since Christmas Day, and I love it.\nIt came in a small box, all tidy and wanting to be built on Christmas day\nTaking it all out of the box, you get the rain water measurer, wind direction, software CD, temp and wireless sensor and a cover to protect it, wind speed and all the fixing clamps needed.\n","title":"My Weather station","type":"articles"},{"content":"When you start to play with the Entity Framework you will soon come up with the need to store your connection in a common place. To do this you will need to with provide the connection string to the Entity Object Context or provide the Entity Connection. I prefer to us the Entity Connection as you can explicity define each section of the connection.\nC#\nVB.NET\nand if you need to pass in the UserID and Password\nFor some more help on setting this up check out Ricka on Dynamic Data\n","date":"23 January 2009","externalUrl":null,"permalink":"/creating-an-entity-connection-for-the-entity-framework/","section":"Articles","summary":"When you start to play with the Entity Framework you will soon come up with the need to store your connection in a common place. To do this you will need to with provide the connection string to the Entity Object Context or provide the Entity Connection. I prefer to us the Entity Connection as you can explicity define each section of the connection.\n","title":"Creating an Entity Connection for the Entity Framework","type":"articles"},{"content":"After using StructureMap for a while I thought it would be nice to generate a simple example of how it all works, so I’ve built in Visual Studio 2008, both C# and a VB.NET version.\nStructreMap Example.zip (4.47 kb)\nStructureMapExampleVB.zip (9.41 kb)\nFor more information on StructureMap please go to their main website\nIf you need to know more about IoC’s then it’s worth making a look at the following links:\nInversion of Control\nList of .NET Dependency Injection Containers (IOC)\nIoC Benchmarks\nMVC Storefront: Dependency Injection\nNinJect\n","date":"22 January 2009","externalUrl":null,"permalink":"/structuremap-example/","section":"Articles","summary":"After using StructureMap for a while I thought it would be nice to generate a simple example of how it all works, so I’ve built in Visual Studio 2008, both C# and a VB.NET version.\n","title":"StructureMap Example","type":"articles"},{"content":"What with Entity Framework around, I have been finding it quite hard to find any good information about the Framework, so I have started to compile a list of good resources\nThe ADO.NET Entity Framework Overview\nCode Samples\nMike Taulty is Mr Entity Framework\nProfessional ADO.NET 3.5 with LINQ and the Entity Framework\nEntity Framework Toolkits \u0026amp; Extras\nTransparent Lazy Loading for Entity Framework\n","date":"21 January 2009","externalUrl":null,"permalink":"/linq-to-entity-framework/","section":"Articles","summary":"What with Entity Framework around, I have been finding it quite hard to find any good information about the Framework, so I have started to compile a list of good resources\nThe ADO.NET Entity Framework Overview\n","title":"LINQ to Entity Framework","type":"articles"},{"content":"Have you ever had a table to a lot of rows, when I mean a lot I mean over 1,000,000 records.\nIf you try and perform a row count like\nSELECT COUNT(ID) FROM table\nit just takes forever.\nIf you are running SQL server you can perform a look up in the sysindexes table\nSELECT rows\nFROM sysindexes\nWHERE id = OBJECT_ID(‘table‘)\nAND indid \u0026lt; 2\nmuch fast, but not so easy.\n","date":"19 January 2009","externalUrl":null,"permalink":"/fastest-way-to-find-the-number-of-records-in-ms-sql/","section":"Articles","summary":"Have you ever had a table to a lot of rows, when I mean a lot I mean over 1,000,000 records.\nIf you try and perform a row count like\nSELECT COUNT(ID) FROM table\nit just takes forever.\n","title":"Fastest way to find the number of records in MS SQL","type":"articles"},{"content":"Whatare the differences between LINQ to SQL v LINQ to Entities, well:\nLINQ to SQL uses tables as entities\nLINQ to Entities allows me to write C# LINQ queries that run against a conceptual data model.\nThe following table provides a summary of the features within each LINQ object\nSo this means that LINQ to SQL uses a database model to create its entities, where as the Entity Framework work on a layer of abstraction above the data, this is a most important feature. As most database changes are taken care of by the schema and mapping without requiring a change to the obect model – making it so you do not have to refactor and rebuild your objects.\nThe second difference is the Entity Framework has the ability to allow the entity inheritance and entity composition. This means that you can create an entity that is composed of colums originating in multiple tables without any complex join logic.\nIn summary:\nIf you want the added security of insulation and loose coupling from the underlying database schema to make your object model more resilient to change, use the Entity Framework If you find that you need the features of entity inheritance and entity composition, use the Entity Framework If you already have a large LINQ to SQL codebase that is running just fine without entities, you probably don’t need to spend the time to refactor out LINQ to SQL to replace it with LINQ to Entities. If you want to run LINQ queries against an object model, but your object model is a 1:1 mirror of the tables in your database, you probably don’t need the Entity Framework. ","date":"19 January 2009","externalUrl":null,"permalink":"/linq-to-sql-v-linq-to-entities/","section":"Articles","summary":"Whatare the differences between LINQ to SQL v LINQ to Entities, well:\nLINQ to SQL uses tables as entities\nLINQ to Entities allows me to write C# LINQ queries that run against a conceptual data model.\n","title":"LINQ to SQL v LINQ to Entities","type":"articles"},{"content":"Microsoft has released it’s Entity Framework to the work, so does this mean the death of LINQ to SQL? Check out my blog on this, Death of LINQ to SQL\nSo why is LINQ so good, well the problems with data has always been around the different and many way you need to know to interface and programme to. For example if you conntect to a Microsoft SQL Server database, you need to know SQL, to read and write to XML files you need to learn XPath or XQuery, to query Active Directory you need to know LDAP (Lightweigth Directory Access Protocol). To know all of these are more is quite a task.\nSO along comes LINQ, which is a intergrated query language, which provides the same query language and grammer features, no matter where the data is held.\nMicrosoft started off by allowing developers to use LINQ to XML, LINQ to L, and LINQ to Objects. These are all good starting blocks, but I have always been aware that Microsofts intention has been to pull all of these together and under one method, and that is the Entity Framework. Which is built on top of LINQ and ADO.NET 3.0.\nIn order to use the Entity Framework you will nedd Visual Studio 2008, along with Service Pack 1 and .NET 3.5\nDefining an Entiry Data Model\nOnce you have created your project, say an Console Application, you can get down to generating an Entity Data Model\nMake sure you have Visual Studio 2008 SP1, otherwisethe Entity Framework will not be available. Add a New Item to your project, and select ADO.NET Entity Data Model. Change the name to read NorthwindModel.edmx Select to Generate From Database Choose you data connection you wish to use, select the Northwind database Save the connection, you should find your app.config should now have the NorthwindEntities Select the database objects you wish to choose, in ower example select Customer, Orders, Order Details and Products. Change the Model Namespace to NorthwindModel and click finish. You should end up with an .EDMX file looking something like this: Okay, now it is time to query the data\nQuerying Products\nWhat is nice about LINQ is it looks and feels very much like SQL. With one exception, you have to write the syntax back to front. Why I hear you ask, I don’t know the official answer to this, but my thoughts are that it is due to intellisense, as by writing you syntax backwards the intellisense can find the information you need.\nOkay to query the Products table, you will first need to create an instance of the NorthwindEntities Class, where did this come from? Well it was created when you created the .edmx file.\nNorthwindEntities entities = new NorthwindEntities();\nDim db As New NorthwindEntities()\nNext we have to create the LINQ statement to read the Products table / entity\nvar products = from p in entities.Products\nwhere p.ProductID == 7\nselect p;\nDim products = From p In entities.Products _\nWhere p.ProductID = 7 _\nSelect p\nOkay now you have the products you can loop through the list by using a For Each method foreach (var p in products) { Console.WriteLine(p.ProductName); } For Each p In products Console.WriteLine(p.ProductName) Next How simple could it be? Check out my other blog entries in using LINQ to find out more information on what you can do with LINQ To find out more about LINQ and the Entiry Framework check out The ADO.NET Entity Framework OverviewThe ADO.NET Entity Framework Overview or Introduction to ASP.NET Dynamic Data\n","date":"19 January 2009","externalUrl":null,"permalink":"/linq-entity-framework/","section":"Articles","summary":"Microsoft has released it’s Entity Framework to the work, so does this mean the death of LINQ to SQL? Check out my blog on this, Death of LINQ to SQL\nSo why is LINQ so good, well the problems with data has always been around the different and many way you need to know to interface and programme to. For example if you conntect to a Microsoft SQL Server database, you need to know SQL, to read and write to XML files you need to learn XPath or XQuery, to query Active Directory you need to know LDAP (Lightweigth Directory Access Protocol). To know all of these are more is quite a task.\n","title":"LINQ Entity Framework","type":"articles"},{"content":"Programming in different languages is not an easy process, often getting confused at which syntax to use. There are many online code converters\n","date":"19 January 2009","externalUrl":null,"permalink":"/easy-way-to-go-from-c-to-vb/","section":"Articles","summary":"Programming in different languages is not an easy process, often getting confused at which syntax to use. There are many online code converters\n","title":"Easy way to go from C# to VB","type":"articles"},{"content":"Well it just had to happen, on Friday my iPhone slipped out of my hand and hit the floor flat on the screen.\nSo a call to Apple support informed me that it will cost £206 to get repaired 🙁\nSo just ordered a Nokia 8310 as a replacement, for the time being.\n","date":"18 January 2009","externalUrl":null,"permalink":"/woops-dropped-iphone/","section":"Articles","summary":"Well it just had to happen, on Friday my iPhone slipped out of my hand and hit the floor flat on the screen.\nSo a call to Apple support informed me that it will cost £206 to get repaired 🙁\n","title":"Woops, dropped iPhone","type":"articles"},{"content":" It’s nice to use SubVersion locally, after seeing that CodePlex now supporting SVN over HTTP, I thought I’d give it ago. Here all all the steps for allowing you to use SVN via port 80 and SVN:\nThe subversion server, download the source, not third party application, installer at http://subversion.tigris.org/project_packages.html\ndoes not include Apache, it includes the subversion modules that work with apache but not apache itself.\nAfter installing the package you will need to set svnserve up to be a service, there are instructions for this at:\nhttp://svn.collab.net/repos/svn/trunk/notes/windows-service.txt\nEssentially you need to do:\nmd c:\\subversion-repositories\nsc create Subversion binpath= “c:\\program files\\subversion\\bin\\svnserve.exe –service -r c:\\subversion-repositories” displayname= “Subversion Server” depend= Tcpip\nThen\nnet start Subversion\nThis sets up the subversion service and starts it, you will then need to create your repository\n“c:\\program files\\subversion\\bin\\svnadmin” create c:\\subversion-repositories\\repos\nYou now have a svn server running with a repository called my-repos available at svn://\u0026lt;server-ip\u0026gt;/repos\nAt this point the repository will be set to anonymous read access and auth write access but will not have any authentication setup, to set this up go into the c:\\subversion-repositories\\repos\\conf folder and edit authz and passwd files to setup the permissions, they are comments and fairly easy to understand.\nI’ve attached two working examples for authentication, to help the configuration.\nsvnserve.conf (413.00 bytes)\npasswd (51.00 bytes)\n","date":"15 January 2009","externalUrl":null,"permalink":"/create-subversion-on-an-internet-machine-via-port-80/","section":"Articles","summary":" It’s nice to use SubVersion locally, after seeing that CodePlex now supporting SVN over HTTP, I thought I’d give it ago. Here all all the steps for allowing you to use SVN via port 80 and SVN:\n","title":"Create SubVersion on an Internet machine via port 80","type":"articles"},{"content":"I’ve been using LINQ to SQL for some time, and each time I come back to the same example, so it’s about time I shared the example:\n// Create a DataContext.\nNorthwind db = new Northwind();\n// Retrieve customer LAZYK.\nCustomer cust = (from c in db.Customers\nwhere c.CustomerID == “LAZYK”\nselect c).Single\u0026lt;Customer\u0026gt;();\n// Update the contact name.\ncust.ContactName = “John Smith”;\ntry\n{\n// Save the changes.\ndb.SubmitChanges();\n}\n// Detect concurrency conflicts.\ncatch (ChangeConflictException)\n{\n// Resolve conflicts.\ndb.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);\n}\n","date":"15 January 2009","externalUrl":null,"permalink":"/simple-linq-2-sql-example/","section":"Articles","summary":"I’ve been using LINQ to SQL for some time, and each time I come back to the same example, so it’s about time I shared the example:\n// Create a DataContext.\nNorthwind db = new Northwind();\n","title":"Simple LINQ 2 SQL example","type":"articles"},{"content":"Microsoft have release the January CTP edition of the Windows Azure Tools and SDK Kit\nWindows Azure Software Development Kit (January 2009 CTP)\nWindows Azure Tools for Microsoft Visual Studio January 2009 CTP\nThese newly released SDK and Tools include:\nBug and performance fixes Improved integration with Visual Studio Performance improvements with execution and debugging scenarios Improvements to Storage Client and ASP.Net provider samples Added support to debug Silverlight in a web role ","date":"15 January 2009","externalUrl":null,"permalink":"/january-2009-ctp-of-the-windows-azure-tools-and-sdk-released/","section":"Articles","summary":"Microsoft have release the January CTP edition of the Windows Azure Tools and SDK Kit\nWindows Azure Software Development Kit (January 2009 CTP)\nWindows Azure Tools for Microsoft Visual Studio January 2009 CTP\n","title":"January 2009 CTP of the Windows Azure Tools and SDK released","type":"articles"},{"content":"How many times have you seen this happen?\n","date":"14 January 2009","externalUrl":null,"permalink":"/over-complicated/","section":"Articles","summary":"How many times have you seen this happen?\n","title":"Over complicated","type":"articles"},{"content":"Following all the hype at PDC last year, Microsoft have not released Windows 7 Beta, download\nCut to the chase and go directly to the download\nI’ve also managed to download a copy and place it on my server, but you’ll need a username and password to get the ISO file.\n","date":"9 January 2009","externalUrl":null,"permalink":"/windows-7-available-for-download/","section":"Articles","summary":"Following all the hype at PDC last year, Microsoft have not released Windows 7 Beta, download\nCut to the chase and go directly to the download\nI’ve also managed to download a copy and place it on my server, but you’ll need a username and password to get the ISO file.\n","title":"Windows 7 available for download","type":"articles"},{"content":"We’ll I’ve not started with Windows 7 yet, but I’d thought I’d kick off with a cartoon\n","date":"9 January 2009","externalUrl":null,"permalink":"/windows-7/","section":"Articles","summary":"We’ll I’ve not started with Windows 7 yet, but I’d thought I’d kick off with a cartoon\n","title":"Windows 7","type":"articles"},{"content":"Microsoft has released BizSpark, produced for the new start up development businesses that need to get going with all the latests technology. Providing the software, support and visibility required for a small business.\nhttp://www.microsoft.com/bizspark/Default/\nWhat are you waiting for?\nAnother method for aquiring the latest technology is through the Microsoft Partner Programme, which provides all the software you need to start selling Microsoft products for just £199, it does not however include any development tools.\n","date":"6 January 2009","externalUrl":null,"permalink":"/development-software-for-small-startups/","section":"Articles","summary":"Microsoft has released BizSpark, produced for the new start up development businesses that need to get going with all the latests technology. Providing the software, support and visibility required for a small business.\nhttp://www.microsoft.com/bizspark/Default/\n","title":"Development software for small startups","type":"articles"},{"content":"It’s nice to know who and when people are logging on to your servers, here is a very simple way of recording someone logging on and logging off the server\nCreate a file called:\nlogon.cmd\necho logon %username% %computername% %date% %time% \u0026gt;\u0026gt; “C:\\logon.log”\nlogoff.cmd\necho logoff %username% %computername% %date% %time% \u0026gt;\u0026gt; “C:\\logon.log”\nUpdate ther Group Policy, via gpedit.msc User Configuration-\u0026gt; Windows Settings-\u0026gt; Scripts (Logon/Logoff)-\u0026gt; Logon\nUser Configuration-\u0026gt; Windows Settings-\u0026gt; Scripts (Logon/Logoff)-\u0026gt; Logoff\nWhen the users log on and off a log file will be updated\n","date":"5 January 2009","externalUrl":null,"permalink":"/tracking-server-logins/","section":"Articles","summary":"It’s nice to know who and when people are logging on to your servers, here is a very simple way of recording someone logging on and logging off the server\nCreate a file called:\nlogon.cmd\n","title":"Tracking Server Logins","type":"articles"},{"content":"Chrome\nIn the Google Chrome’s address bar type:\nabout:internets (XP only)\nabout:stats\nabout:memory\nabout:network\nabout:histograms\nabout:dns\nabout:cache\nabout:plugins\nabout:version\nGoogle Earth\nClick [CTRL] + [ALT] + [A] in Google Earth to launch a Flight Simulator\n","date":"3 January 2009","externalUrl":null,"permalink":"/googles-hidden-gems/","section":"Articles","summary":"Chrome\nIn the Google Chrome’s address bar type:\nabout:internets (XP only)\nabout:stats\nabout:memory\nabout:network\nabout:histograms\nabout:dns\nabout:cache\nabout:plugins\nabout:version\n","title":"Googles hidden gems","type":"articles"},{"content":"The latest fad is to create Carousels to display images, and allow for easy navigation. I have not been able to find any .NET controls to enable you to create a Carousel on a web page.\n[usercontrol:~/User controls/carousel.ascx] So I set myself the task of generating a web page control to allow for easy, managed code, configuration of a Carousel Control in .NET First I went on the hunt for a simple javaScript Carousel that I could use, I found a lovely Carousel by Doug Greenall, the information on his blog goes in to great detail of how the Carousel works, but this was not intention to go in to detail about the inner working of a Carousel. So I downloaded Doug Greenall's Carousel and then went to adapt the javaScript code to create a single DLL Control that could be reused. The end product is a small DLL that can be dragged and dropped in to your ASP.NET application or Website Carousel.dll (21.50 kb) The project solution was generated using Visual Studio 2008 Pro,with a Target Framework of \".NET Framework 2.0\" Carousel.zip (191.73 kb) How to use the Carousel Okay, so now I've built the Carousel Control, you now want to to know how to use it? First create a new WebSite Add the Carousel.dll or a project reference to your website On the web page register the control (or add it to your web.config) Then add the control to the page, as seen below Next in the code behind you need to add to the CarouselDetail collection, which will add the images, links to the Carousel And that is it, the more you add to the CarouselDetail collection the more items will appear on the Carousel. ","date":"22 December 2008","externalUrl":null,"permalink":"/how-to-create-a-carousel-in-a-webpage/","section":"Articles","summary":"The latest fad is to create Carousels to display images, and allow for easy navigation. I have not been able to find any .NET controls to enable you to create a Carousel on a web page.\n","title":"How to create a Carousel in a webpage","type":"articles"},{"content":"I've always been able to create a standalone DLL control that can be reused in other web applications. I've never really found out how to embed other resources, or more to the point JavaScript files.\nUntil now\nHere's how to embed the file:\nCreate a js file such as carousel.js In Visual Studio, select the file in Solution Explorer and change the Build Action property to \"Embedded Resource\" Build the project and the carousel.js file is now part of the assembly (you don't need to distibute the js file now it's part of the assembly) Now to get the resource out using code:\nSo if we have a resource named Control.carousel.js we can use the following to include it in our page:\nSystem.IO.Stream script = Assembly.GetExecutingAssembly().GetManifestResourceStream(\"Control.carousel.js\");\nSystem.IO.StreamReader sr = new System.IO.StreamReader(script);\nPage.ClientScript.RegisterClientScriptBlock(GetType(), \"carousel\", sr.ReadToEnd().ToString(), true);\nsr.Close();\nThe above code injects the embedded file in to the page, how easy could it be? ","date":"22 December 2008","externalUrl":null,"permalink":"/embedding-javascript-in-an-assembly/","section":"Articles","summary":"I've always been able to create a standalone DLL control that can be reused in other web applications. I've never really found out how to embed other resources, or more to the point JavaScript files.\n","title":"Embedding javascript in an assembly","type":"articles"},{"content":"One of the tasks Jon was given was to create an Audit module for LINQ, and came across this link which seems to provide a solution. I’ve not had time to go over the solution, but it appears to do a very good job at first glance.\nLINQ to SQL Audit Trail LINQ Audit Trail v2 – DoddleAudit\n","date":"20 December 2008","externalUrl":null,"permalink":"/generating-an-audit-for-linq/","section":"Articles","summary":"One of the tasks Jon was given was to create an Audit module for LINQ, and came across this link which seems to provide a solution. I’ve not had time to go over the solution, but it appears to do a very good job at first glance.\n","title":"Generating an Audit for LINQ","type":"articles"},{"content":"Do you still use Notepad that ships with Windows?\nI did, until I found NotePad2, it’s fast, it’s easy to use, and more to the point it works.\nI’ve been using it for the past 2 months, and I have not got any clue to the features, but what I like about it is it just works and is a very good replacement for the standard Windows Notepad. Here are the features, cribbed from the NotePad2 Website:\nCustomizable syntax highlighting: HTML, XML, CSS, JavaScript, VBScript, ASP, PHP, CSS, Perl/CGI C/C++, C#, Java, VB, Pascal, Assembler, SQL, Python, NSIS INI, REG, INF, BAT, DIFF Drag \u0026amp; drop text editing inside and outside Notepad2 Basic regular expression search and replace Useful word, line and block editing shortcuts Rectangular selection (Alt+Mouse) Brace matching, auto indent, long line marker, zoom functions Support for Unicode, UTF-8, Unix and Mac text files Open shell links Mostly adjustable Auto indentation Bracket matching Encoding conversion between ASCII, UTF-8 and UTF-16 formats Multiple undo/redo; rectangular block selection Newline conversion, between DOS (CR/LF), Unix (LF) and Mac (CR) formats How to Replace notepad with notepad2 in Vista? First you need to download notepad2 from here First you need to Rename Notepad2.exe to notepad.exe. Find c:\\windows\\notepad.exe and c:\\windows\\system32\\notepad.exe and set the owner to ‘Administrators’, and grant Administrators full control. Using Windows Explorer, drag and drop the renamed notepad2.exe to c:\\windows and c:\\windows\\system32. Optional replace the permissions on the new notepad.exe to Read \u0026amp; Execute and Read. notepad2.zip (257.82 kb) Another one to look at is Notepad++, it has a lovely set of plugins such as XML have a look at Tim Almonds post on the XML plugin ","date":"19 December 2008","externalUrl":null,"permalink":"/small-free-and-replacement-for-notepad/","section":"Articles","summary":"Do you still use Notepad that ships with Windows?\nI did, until I found NotePad2, it’s fast, it’s easy to use, and more to the point it works.\nI’ve been using it for the past 2 months, and I have not got any clue to the features, but what I like about it is it just works and is a very good replacement for the standard Windows Notepad. ","title":"Small free and replacement for Notepad","type":"articles"},{"content":"Microsoft® Silverlight™ Tools for Visual Studio 2008 SP1\nIf you going to do anything with Silverlight you’re going to have to get Blend to:\nMicrosoft Expression Blend™ 2 Trial\nMicrosoft Expression Blend™ 2 Service Pack 1 New to Silverlight?\nVideos Video Tutorials in One Place\n","date":"18 December 2008","externalUrl":null,"permalink":"/getting-started-with-silverlight/","section":"Articles","summary":"Microsoft® Silverlight™ Tools for Visual Studio 2008 SP1\nIf you going to do anything with Silverlight you’re going to have to get Blend to:\nMicrosoft Expression Blend™ 2 Trial\nMicrosoft Expression Blend™ 2 Service Pack 1 ","title":"Getting Started with Silverlight","type":"articles"},{"content":"I have a a wobble board for my Wii and I am looking for a game to play at Xmas, but which one?\n","date":"18 December 2008","externalUrl":null,"permalink":"/which-game-for-christmas/","section":"Articles","summary":"I have a a wobble board for my Wii and I am looking for a game to play at Xmas, but which one?\n","title":"Which game for Christmas?","type":"articles"},{"content":"After my work creating the Mad Tri web site, I submitted the theme it to the BlogEngine team a few months ago and they have included it in their Theme pack, what a lovely surprise.\nThe BlogEngine team are going to be working hard over Christmas, with updating the BlogEngine and release a new release. more…\nI too are going to the working over the Christmas on an Enhanced Newsletter and a Resource Editor to enable changes to Internationalization from the web, power to the BlogEngine ","date":"18 December 2008","externalUrl":null,"permalink":"/my-theme-made-it-in-to-the-blogengine-themes/","section":"Articles","summary":"After my work creating the Mad Tri web site, I submitted the theme it to the BlogEngine team a few months ago and they have included it in their Theme pack, what a lovely surprise.\nThe BlogEngine team are going to be working hard over Christmas, with updating the BlogEngine and release a new release. more…\n","title":"My Theme made it in to the BlogEngine Themes","type":"articles"},{"content":"\n","date":"18 December 2008","externalUrl":null,"permalink":"/i-came-from-a-distant-planet/","section":"Articles","summary":"\n","title":"I came from a distant planet…","type":"articles"},{"content":"Need to check out Transaction Scope\n","date":"17 December 2008","externalUrl":null,"permalink":"/transaction-scope/","section":"Articles","summary":"Need to check out Transaction Scope\n","title":"Transaction Scope","type":"articles"},{"content":"The purpose of the class is to allow the application to display information to the end user.\nAll that is required is for the calling application to set the Message in the PageNotifications class, e.g.\nGradWeb.Web.Core.PageNotifications.Message= \"Hello Page Notifier\";\nThe theme of the application will handle the rest, as the design will have positioned and created CSS information to display the message.\nOver the course of a page you can add as many message as you like and then will be added to the message.\nNOTE\nWhen the page is reloaded the message/'s will be reset.\nEdit\nDesign Considerations The Page Notification control produces the following HTML\n\u0026lt;div class=\"notificationgroup\"\u0026gt;\u0026lt;div class=\"notification\"\u0026gt;Hello Page Notifier\u0026lt;/div\u0026gt;\u0026lt;div class=\"notification\"\u0026gt;Message 2\u0026lt;/div\u0026gt;\u0026lt;/div\u0026gt; In order to change the look and feel you will require the following style sheet information\nnotificationgroup{}notification{} ","date":"16 December 2008","externalUrl":null,"permalink":"/page-notifications/","section":"Articles","summary":"The purpose of the class is to allow the application to display information to the end user.\nAll that is required is for the calling application to set the Message in the PageNotifications class, e.g.\n","title":"Page Notifications","type":"articles"},{"content":"Oh how I remember those days of page through data, using a GridView controller, or any other controller, lots of coding and so easy to make a mistake.\nJust take a look at http://www.unboxedsolutions.com/sean/archive/2005/12/28/818/ by Sean Chase, and you will see what I mean.\nThings have moved on a bit since those days, and now we have LINQ it is much easier, both directly feeding from LINQ or via methods, both provide the same result.\nLinq DataSource Here is how to enable paging directly to LINQ, by using the LinqDataSource\nHow easy could it be?\nLinq Methods When it comes to generating your own method you can do this with just a little more coding and take advantange of the Linq Skip and Take methods, the sample below provides an example using a Method. To use this fully you will need to make a few changes to the webpage, as shown below:\nNow that you have everything set on the page all that is left is the code behind and the methods, I am using the partial class in the example, but it does not have to be.\nCode Behind\nMethods To ensure that the application is Paging correctly I found running the SQL Profiler on the database made sure that only the data page was being returned and nothing else, you may want to perform your own tests too.\nI have included a small application using Visual Studio 2008 and .NET 3.5, all you will need to change is the connection string settings to the NorthWind database. GridPerformance.zip (16.46 kb)\n","date":"15 December 2008","externalUrl":null,"permalink":"/linq-to-sql-and-paging/","section":"Articles","summary":"Oh how I remember those days of page through data, using a GridView controller, or any other controller, lots of coding and so easy to make a mistake.\nJust take a look at http://www.unboxedsolutions.com/sean/archive/2005/12/28/818/ by Sean Chase, and you will see what I mean.\n","title":"LINQ to SQL and Paging","type":"articles"},{"content":"http://blog.lavablast.com/post/2008/02/RESX-file-Web-Editor/\nResXEditor.zip (1.01 mb)\n","date":"12 December 2008","externalUrl":null,"permalink":"/editable-resource-files/","section":"Articles","summary":"http://blog.lavablast.com/post/2008/02/RESX-file-Web-Editor/\nResXEditor.zip (1.01 mb)\n","title":"Editable Resource Files","type":"articles"},{"content":"With C# 4.0 going to include Dynamic Language programming, the reports and demos I have seen to date look very impressive.\nThe only main implementation and useful application was to connect to COM objects, or more to the point to Microsoft Office as this is pure COM, and always been really hard to connect and work with. I've also seen a demo of using the Dynamic Language to build your own .NET compiler on the fly, so building and running C# code from your own application, how cool is that?\nWith Dynamic Language for C#, COM should be eaiser to work with.\nMicrosoft have release the Dynamic Language Runtime on CodePlex so we can start to play with the new features before they are release in C# 4.0\n","date":"11 December 2008","externalUrl":null,"permalink":"/c-4-0-dynamic-language/","section":"Articles","summary":"With C# 4.0 going to include Dynamic Language programming, the reports and demos I have seen to date look very impressive.\nThe only main implementation and useful application was to connect to COM objects, or more to the point to Microsoft Office as this is pure COM, and always been really hard to connect and work with. ","title":"C# 4.0 Dynamic Language","type":"articles"},{"content":"What is the best practice and pattern to use for the DataContext with LINQ to SQL.\nWhile using LINQ to SQL and it's DataContext I have found it is very easy to fall in to a concurrency issues when you try out multiusers, I've not found the answer as yet, but I have come across this article for different methods\nBest practice and effective way of using DataContext in Linq to SQL?\n","date":"10 December 2008","externalUrl":null,"permalink":"/datacontext-in-linq-to-sql/","section":"Articles","summary":"What is the best practice and pattern to use for the DataContext with LINQ to SQL.\nWhile using LINQ to SQL and it's DataContext I have found it is very easy to fall in to a concurrency issues when you try out multiusers, I've not found the answer as yet, but I have come across this article for different methods\n","title":"DataContext in LINQ to SQL","type":"articles"},{"content":"One little crip I am having with LINQ to SQL is that when you build the DBML files within Visual Studio 2008, the default values from the database are not taken in to account.\nThis means that you need to set the default values against your object before it is saved or after the object is created.\nThis is a pain the the back side. This articles provides a method to overcome this “Handling Default Values With LINQ to SQL“\n","date":"9 December 2008","externalUrl":null,"permalink":"/linq-2-sql-default-values/","section":"Articles","summary":"One little crip I am having with LINQ to SQL is that when you build the DBML files within Visual Studio 2008, the default values from the database are not taken in to account.\nThis means that you need to set the default values against your object before it is saved or after the object is created.\n","title":"LINQ 2 SQL default values","type":"articles"},{"content":"List of files and links as part of my Grog talk at DotNetDevNet 2nd December 2008 •CodePlex –http://www.codeplex.com/ •VisualStudio Team System 2008 Team Explorer –http://tinyurl.com/VSTM-TeamExplorer •SubVersion –http://subversion.tigris.org/ •CodePlex Blog –http://blogs.msdn.com/codeplex/ CodePlex.ppsx (571.84 kb)\nCodePlex.ppsx (571.84 kb)\nCodePlex.ppt (664.50 kb)\n","date":"2 December 2008","externalUrl":null,"permalink":"/codeplex-presentation/","section":"Articles","summary":"List of files and links as part of my Grog talk at DotNetDevNet 2nd December 2008 •CodePlex –http://www.codeplex.com/ •VisualStudio Team System 2008 Team Explorer –http://tinyurl.com/VSTM-TeamExplorer •SubVersion –http://subversion.tigris.org/ •CodePlex Blog –http://blogs.msdn.com/codeplex/ ","title":"CodePlex Presentation","type":"articles"},{"content":"Here is a set of link you may need to get you going with Azure and the Microsoft Cloud\nDDD7 presentation by Chris Hay, includes Power Point Presentation and Source Code, this is the best examples I have see to date\nWelcome To The Cloud (Complete).zip (2.41 mb) Here are a few links I have found on my travels, that will help getting going Windows Azure How Do I Videos\nCnet News Article Windows azure developer starter guide\nWindows Azure – What Happens in the Data Center? The cloud for a fast deployment of proof of concepts Question and Answers\nThe Azure Services Platform is designed to help developers quickly and easily create, deploy, manage, and distribute web services and applications on the Internet. Windows Azure is an operating system for the cloud that serves as the development, run-time, and control environment for the Azure Services Platform. Windows Azure provides developers on-demand compute \u0026amp; storage to host, scale, and manage web applications on the internet through Microsoft data centers. Windows Azure is elastic, flexible, and interoperable. With Windows Azure developers can achieve high levels of service availability and application interoperability while maintaining freedom of choice. The Windows Azure SDK provides developers with the tools and APIs needed to develop, deploy, and manage scalable services in Windows Azure. Software Development Kit The Azure Services Training Kit will include a comprehensive set of technical content including samples, demos, hands-on labs, and presentations that are designed to help you learn how to use the Azure Services Platform. This initial PDC Preview release includes the hands-on labs that were provided at the PDC 2008 conference. These labs cover the broad set of Azure Services including Windows Azure, .NET Services, SQL Services, and Live Services. Additional content will be included in future updates of this kit.\nTraining Kit\nWindows Azure Tools for Microsoft Visual Studio extend Visual Studio to enable the creation, building, debugging, running and packaging of scalable services on Windows Azure. Windows Azure Tools for Microsoft Visual Studio includes:\nC# and VB Project templates for building Cloud Services Integration with the Development Fabric and Development Storage services Debugging Cloud Service Roles running in the Development Fabric Building and packaging of Cloud Service Packages Browsing to the Azure Services Developer Portal Role configuration SSL Certificate selection Tools for Microsoft Visual Studio\nFive webcasts for Azure to help you along the way\nPart: 1 Azure Services for Developers: Fundamentals Part: 2 Azure Services for Developers: Developing a Windows Azure Application Part: 3 Azure Services for Developers: .NET Services Part: 4 Azure Services for Developers: Microsoft SQL Data Services Part: 5 Azure Services for Developers: Live Framework Services Windows Azure and SQL Data Services Talk for .NET Developer Network\n","date":"25 November 2008","externalUrl":null,"permalink":"/links-for-the-cloud/","section":"Articles","summary":"Here is a set of link you may need to get you going with Azure and the Microsoft Cloud\nDDD7 presentation by Chris Hay, includes Power Point Presentation and Source Code, this is the best examples I have see to date\n","title":"Links for The Cloud","type":"articles"},{"content":"Okay it has taken me quite a while, but I finally found this Blog on how to publish to the Microsoft Cloud. A STEP BY STEP GUIDE\nNot for getting you'll need an activation key Id to enable your services, I'm still trying to get mine. ","date":"24 November 2008","externalUrl":null,"permalink":"/how-to-publish-to-the-cloud/","section":"Articles","summary":"Okay it has taken me quite a while, but I finally found this Blog on how to publish to the Microsoft Cloud. A STEP BY STEP GUIDE\nNot for getting you'll need an activation key Id to enable your services, I'm still trying to get mine. ","title":"How to publish to the Cloud","type":"articles"},{"content":"With Microsofts Cloud now available in CTP, I am looking at writing a blog entry about this great technology, but in the mean time if you are planning to use the Azure Tables, then it is worth checking out Chris Hays blog on Azure Tables\nAzure Tables, Entities and Partition Diagrams\nIt give a good explaination of the Partition Key. ","date":"24 November 2008","externalUrl":null,"permalink":"/tables-in-the-cloud/","section":"Articles","summary":"With Microsofts Cloud now available in CTP, I am looking at writing a blog entry about this great technology, but in the mean time if you are planning to use the Azure Tables, then it is worth checking out Chris Hays blog on Azure Tables\n","title":"Tables in the Cloud","type":"articles"},{"content":"Always good to go back to basics, where ever I go I have the need to generate a security environment which is based on the MembershipProvider.\nThere are lots of examples out on the Internet so it makes it hard to find what you are after, everytime I end up back at the same website, as it take you through the basic Membership and then goes in to it in depth, such as switching users if you are an administrator.\nExamining ASP.NET 2.0’s Membership, Roles, and Profile\nManage Custom Security Credentials the Smart (Client) Way\nNot every application is a Web Based application, people still create WinForm application, so if you are using a WinForm application it’s worth looking at this article\nUsing the ASP.NET membership provider in a Windows forms application\n","date":"24 November 2008","externalUrl":null,"permalink":"/membership-and-security/","section":"Articles","summary":"Always good to go back to basics, where ever I go I have the need to generate a security environment which is based on the MembershipProvider.\nThere are lots of examples out on the Internet so it makes it hard to find what you are after, everytime I end up back at the same website, as it take you through the basic Membership and then goes in to it in depth, such as switching users if you are an administrator.\n","title":"Membership and Security","type":"articles"},{"content":"Just been playing with Live Mesh Beta.\nSo easy to setup, just visit https://www.mesh.com\nYou can either run the application from the web browser, or install a local client to your PC.\nSo I went to take and install the local client on my machine at home, asked it to share a few files, well I also choose a complete folder which contains about 25 Gbyes of information.\nWhen I got to work I went to Live Mesh, sign in, using my MSN login, and as if by magic it appeared I could see all my files. Only issue I had was that the limit of 5 Gbytes was hit. So I removed the large folder from the Mesh, and everything was fine.\nI install the Live Mesh local on my machine at work, again very simple, and wow I had my files on my desktop, a simple sync process and I could open my files, edit and save them as if they where local.\nWhen you are in a Live Mesh folder, a small bar on the right handside appears which allows you to connect with any machine you have registered, but then I caught sight of Live Desktop, click on it, a small ActiveX install and, hay, I have full access to my home desktop from anywhere on the Internet. I am so impressed.\nThe current limit of 5 Gbytes of storage space can be a bit limited at present, but I heard on the grape vine that you can tweek Live Mesh to work Peer to Peer and by pass the Live Mesh online storage.\nOverall I am very impressed, it might be in Beta and only provide 5Gbytes of space, but it solves a long standing issue of beable to access your files from anywhere. It will be interesting to see what business model Microsoft is to use with Live Mesh goes live. ","date":"21 November 2008","externalUrl":null,"permalink":"/live-mesh/","section":"Articles","summary":"Just been playing with Live Mesh Beta.\nSo easy to setup, just visit https://www.mesh.com\nYou can either run the application from the web browser, or install a local client to your PC.\nSo I went to take and install the local client on my machine at home, asked it to share a few files, well I also choose a complete folder which contains about 25 Gbyes of information.\n","title":"Live Mesh","type":"articles"},{"content":"There is an increasing number of Team Foundation Server Addon's, here are a list that might be of use Working remotely and need to collaborate, check this out Working Skype Collaboration Provider for TFS\n","date":"18 November 2008","externalUrl":null,"permalink":"/team-foundation-server-addons/","section":"Articles","summary":"There is an increasing number of Team Foundation Server Addon's, here are a list that might be of use Working remotely and need to collaborate, check this out Working Skype Collaboration Provider for TFS\n","title":"Team Foundation Server Addon’s","type":"articles"},{"content":"I’ll start this article, and list different ways to perform Web Testing Web testing using Fiddler\nAn old favourite of mine Microsoft Web Application Stress Testing\nI am sure there are lots of different Web testing tools, and as I find them I will try and list them here. Web Capacity Analysis Tool\nThe Grinder\nApache JMeter\n","date":"18 November 2008","externalUrl":null,"permalink":"/web-testing/","section":"Articles","summary":"I’ll start this article, and list different ways to perform Web Testing Web testing using Fiddler\nAn old favourite of mine Microsoft Web Application Stress Testing\nI am sure there are lots of different Web testing tools, and as I find them I will try and list them here. ","title":"Web Testing","type":"articles"},{"content":"QUESTION: What is the easiest way to find the difference between two dates?\nDateTime userLoginTime = (DateTime)roteTimeout.LastLoginTime;\nTimeSpan span = DateTime.Now.Subtract(userLoginTime);\nif (span.Seconds \u0026gt; userTimeout.TimeoutPeriod) {\n} ","date":"18 November 2008","externalUrl":null,"permalink":"/difference-between-two-dates/","section":"Articles","summary":"QUESTION: What is the easiest way to find the difference between two dates?\nDateTime userLoginTime = (DateTime)roteTimeout.LastLoginTime;\nTimeSpan span = DateTime.Now.Subtract(userLoginTime);\nif (span.Seconds \u003e userTimeout.TimeoutPeriod) {\n} ","title":"Difference between two dates","type":"articles"},{"content":"Have you tried to write to the Event Log from within your application?\nIt's not hard to write to the Event Log these days, in fact .Net makes it quite easy.\nWhere the issue come is when you deploy your application you find the the operating environment does not have enough permissions. I found a good article this morning on how to over come this by Rory Primrose\nhttp://www.neovolve.com/post/2008/11/12/Creating-event-log-sources-without-administrative-rights/ ","date":"15 November 2008","externalUrl":null,"permalink":"/writing-to-the-event-log-from-your-application/","section":"Articles","summary":"Have you tried to write to the Event Log from within your application?\nIt's not hard to write to the Event Log these days, in fact .Net makes it quite easy.\nWhere the issue come is when you deploy your application you find the the operating environment does not have enough permissions. I found a good article this morning on how to over come this by Rory Primrose\n","title":"Writing to the Event Log from your Application","type":"articles"},{"content":"\nIntroduction I will take you through how to deploy your own Custom Data Process Extension for SQL Server Reporting Server 2005, both on the server and for use within your development environment.\nBackground I've been using and writing Reports for SQL Server Reporting Services for some time now, and it has come time to write my own Security Implementation for the reports. In order for me to do this, I needed to find out how to change the Data Sources within Reporting Services.\nI did find some resource information on Microsoft TechNet: Implementing a Data Processing Extension. I found this article both useful and hard to follow, hence I have written this CodeProject article to help you get up and going as quickly as possible.\nPrerequisites I assume you are familiar with SQL Reporting Services, what they are, design, and installation. For more info about this subject, click here. You should have SQL Reporting Services 2005 already installed. Visual Studio 2005 with SQL Server Reporting Services Report Templates installed. Compile the Custom Data Source Extension After loading the source code, you will need to reference the \"Reporting Services Interfaces\". In my case, it is located in: C:\\Program Files\\Microsoft SQL Server\\90\\SDK\\Assemblies\\Microsoft.ReportingServices.Interfaces.dll; however, this may differ for your installation.\nOnce you have made the reference, you should be able to compile the application.\nInstallation of the Custom Data Source After downloading the source above for the custom data processing extension, you must install it to enable access. The installation process is performed in two steps:\nInstalling and configuring the extension. Configuring extension security. This particular extension is used both by the Reporting Server and within the Visual Studio 2005 Report Designer; both have a different location for configuration, either on the server or your development machine. However both configurations are very similar.\nDevelopment Installation Two configuration files are required to be changed in order for you to be able to see your Custom Data Source from within the development environment. These files typically are held in C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE\\PrivateAssemblies; these files are:\nRSReportDesigner.config RSPreviewPolicy.config Copy your assembly First, you need to copy the Custom Data Source files to the \"PrivateAssemblies\" folder, as this is where they are referenced.\nSetup the configuration file The RSReportDesigner.config holds the reference to the Extension. The following needs to be added to the \u0026lt;Data\u0026gt; tag within the \u0026lt;Extension\u0026gt; tag:\nCollapse \u0026lt;Extension Name=\"CUSTOM_DATASOURCE\" Type=\"DataSourceExtension.DataSetConnection, DataSourceExtension\" /\u0026gt; In order for the designer to use the Custom Data Source, you need to add the following to the \u0026lt;Designer\u0026gt; tag, usually situated just below the \u0026lt;Data\u0026gt; tag:\nCollapse \u0026lt;Extension Name=\"CUSTOM_DATASOURCE\" _Type=\"Microsoft.ReportingServices.QueryDesigners.GenericQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u0026gt; You will notice that this time we are pointing to the standard Microsoft Generic Query Designer. This is because we are trying to build a Custom Data Source Extension and not a Query Designer.\nWhat you should end up with is a RSReportDesigner.config file, looking something like this:\nCollapse \u0026lt;Configuration\u0026gt; \u0026lt;Add Key=\"SecureConnectionLevel\" Value=\"0\" /\u0026gt; \u0026lt;Add Key=\"InstanceName\" Value=\"Microsoft.ReportingServices.PreviewServer\" /\u0026gt; \u0026lt;Add Key=\"SessionCookies\" Value=\"true\" /\u0026gt; \u0026lt;Add Key=\"SessionTimeoutMinutes\" Value=\"3\" /\u0026gt; \u0026lt;Add Key=\"PolicyLevel\" Value=\"rspreviewpolicy.config\" /\u0026gt; \u0026lt;Add Key=\"CacheDataForPreview\" Value=\"true\" /\u0026gt; \u0026lt;Extensions\u0026gt; \u0026lt;Render\u0026gt; \u0026lt;Extension Name=\"XML\" Type=\"Microsoft.ReportingServices.Rendering.XmlDataRenderer.XmlDataReport,Microsoft.ReportingServices.XmlRendering\" /\u0026gt; \u0026lt;Extension Name=\"CSV\" Type=\"Microsoft.ReportingServices.Rendering.CsvRenderer.CsvReport,Microsoft.ReportingServices.CsvRendering\" /\u0026gt; \u0026lt;Extension Name=\"IMAGE\" Type=\"Microsoft.ReportingServices.Rendering.ImageRenderer.ImageReport,Microsoft.ReportingServices.ImageRendering\" /\u0026gt; \u0026lt;Extension Name=\"RGDI\" Type=\"Microsoft.ReportingServices.Rendering.ImageRenderer.RemoteGdiReport,Microsoft.ReportingServices.ImageRendering\" Visible=\"false\" /\u0026gt; \u0026lt;Extension Name=\"PDF\" Type=\"Microsoft.ReportingServices.Rendering.ImageRenderer.PdfReport,Microsoft.ReportingServices.ImageRendering\" /\u0026gt; \u0026lt;Extension Name=\"HTML4.0\" Type=\"Microsoft.ReportingServices.Rendering.HtmlRenderer.Html40RenderingExtension,Microsoft.ReportingServices.HtmlRendering\" Visible=\"false\" /\u0026gt; \u0026lt;Extension Name=\"HTML3.2\" Type=\"Microsoft.ReportingServices.Rendering.HtmlRenderer.Html32RenderingExtension,Microsoft.ReportingServices.HtmlRendering\" Visible=\"false\" /\u0026gt; \u0026lt;Extension Name=\"MHTML\" Type=\"Microsoft.ReportingServices.Rendering.HtmlRenderer.MHtmlRenderingExtension,Microsoft.ReportingServices.HtmlRendering\" /\u0026gt; \u0026lt;Extension Name=\"EXCEL\" Type=\"Microsoft.ReportingServices.Rendering.ExcelRenderer.ExcelRenderer,Microsoft.ReportingServices.ExcelRendering\" /\u0026gt; \u0026lt;/Render\u0026gt; \u0026lt;Data\u0026gt; \u0026lt;Extension Name=\"SQL\" Type=\"Microsoft.ReportingServices.DataExtensions.SqlConnectionWrapper,Microsoft.ReportingServices.DataExtensions\" /\u0026gt; \u0026lt;Extension Name=\"OLEDB\" Type=\"Microsoft.ReportingServices.DataExtensions.OleDbConnectionWrapper,Microsoft.ReportingServices.DataExtensions\"/\u0026gt; \u0026lt;Extension Name=\"OLEDB-MD\" Type=\"Microsoft.ReportingServices.DataExtensions.AdoMdConnection,Microsoft.ReportingServices.DataExtensions\"/\u0026gt; \u0026lt;Extension Name=\"ORACLE\" Type=\"Microsoft.ReportingServices.DataExtensions.OracleClientConnectionWrapper,Microsoft.ReportingServices.DataExtensions\"/\u0026gt; \u0026lt;Extension Name=\"ODBC\" Type=\"Microsoft.ReportingServices.DataExtensions.OdbcConnectionWrapper,Microsoft.ReportingServices.DataExtensions\"/\u0026gt; \u0026lt;Extension Name=\"XML\" Type=\"Microsoft.ReportingServices.DataExtensions.XmlDPConnection,Microsoft.ReportingServices.DataExtensions\"/\u0026gt; \u0026lt;Extension Name=\"RS\" Type=\"Microsoft.ReportingServices.DataExtensions.RSDPConnection,Microsoft.ReportingServices.DataExtensions\"/\u0026gt; \u0026lt;Extension Name=\"CUSTOM_DATASOURCE\" Type=\"DataSourceExtension.DataSetConnection, DataSourceExtension\" /\u0026gt;\u0026lt;/Data\u0026gt; \u0026lt;Designer\u0026gt; \u0026lt;Extension Name=\"SQL\" Type=\"Microsoft.ReportingServices.QueryDesigners.VDTQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u0026gt; \u0026lt;Extension Name=\"OLEDB\" Type=\"Microsoft.ReportingServices.QueryDesigners.VDTQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u0026gt; \u0026lt;Extension Name=\"OLEDB-MD\" Type=\"Microsoft.ReportingServices.QueryDesigners.ASQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u0026gt; \u0026lt;Extension Name=\"ORACLE\" Type=\"Microsoft.ReportingServices.QueryDesigners.VDTQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u0026gt; \u0026lt;Extension Name=\"ODBC\" Type=\"Microsoft.ReportingServices.QueryDesigners.VDTQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u0026gt; \u0026lt;Extension Name=\"XML\" Type=\"Microsoft.ReportingServices.QueryDesigners.GenericQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u0026gt; \u0026lt;Extension Name=\"RS\" Type=\"Microsoft.ReportingServices.QueryDesigners.SMQLQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u0026gt; \u0026lt;Extension Name=\"CUSTOM_DATASOURCE\" Type=\"Microsoft.ReportingServices.QueryDesigners.GenericQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u0026gt;\u0026lt;/Designer\u0026gt; \u0026lt;/Extensions\u0026gt; \u0026lt;/Configuration\u0026gt; Security configuration The security is held in the RSPreviewPolicy.config file, which is in the same folder as the configuration file (RSReportDesigner.config). This file provides the security policy for SQL Server Reporting Services and allows access to your DLL.\nCollapse \u0026lt;CodeGroup class=\"UnionCodeGroup\" version=\"1\" PermissionSetName=\"FullTrust\" Name=\"Customer_DataSource\"Description=\"Code group for my Custom DataSource for data processing extension\"\u0026gt;\u0026lt;IMembershipCondition class=\"UrlMembershipCondition\" version=\"1\" Url=\"C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE\\PrivateAssemblies\\DataSourceExtension.dll\"/\u0026gt; \u0026lt;/CodeGroup\u0026gt; Server Installation To configure the Custom Data Extension on the server where your reports will be running, is a case of following the above, except you'll find the configuration files held in a different location, and depending on the installation, they appear in different places. On my installation file, they are all held in C:\\Program Files\\Microsoft SQL Server\\MSSQL.2\\Reporting Services\\ReportServer\\bin and the configuration files are held inC:\\Program Files\\Microsoft SQL Server\\MSSQL.2\\Reporting Services\\ReportServer, with the names of the configuration files being:\nrsreportserver.config rssrvpolicy.config As this is a server install, you will not need to make or add the \u0026lt;Designer\u0026gt; tag.\nTesting of the Custom Data Source Extension In order to test the Custom Data Source Extension, you will need to generate either a report or a Shared Data Source that points to the new custom Data Source Extension.\nCreate a new project within Visual Studio 2005, select a \"Business Intelligence Project\", and select the \"Report Server Project Wizard\" from the list of templates. On the new data type list, you should see \"Custom DataSource Extension\". If, however, you don't, but you do see CUSTOM_DATASOURCE, this means that the configuration has not picked up your DataSourceExtension.dll, and you will need to check over the configuration files.\nEnter a connection string, like the following: \"FileName=C:\\bottles.xml\", you'll find this file at the top in the download section. Click next, this will take you to the \"Design a Query\" screen. Enter the following query: \"select * from company\", as shown below:\nClick Next, and then continue until you have finished creating a report. You should now be able to run the report with the new Custom DataSource Extension that you can customise and shape to your own needs.\nPoints of Interest Now that you have it running and working, it is worth going over how to debug the Custom Data Extension. I was not intending to cover this in this article, and will reference you to Microsoft TechNet on Debugging Data Processing Extension Code, as this should provide you with sufficient information on how to setup debugging.\nHistory First release.\nLicense This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)\nThe original article can be found on CodeProject ","date":"11 November 2008","externalUrl":null,"permalink":"/implementing-a-data-processing-extension/","section":"Articles","summary":"\nIntroduction I will take you through how to deploy your own Custom Data Process Extension for SQL Server Reporting Server 2005, both on the server and for use within your development environment.\nBackground I've been using and writing Reports for SQL Server Reporting Services for some time now, and it has come time to write my own Security Implementation for the reports. In order for me to do this, I needed to find out how to change the Data Sources within Reporting Services.\nI did find some resource information on Microsoft TechNet: Implementing a Data Processing Extension. I found this article both useful and hard to follow, hence I have written this CodeProject article to help you get up and going as quickly as possible.\nPrerequisites I assume you are familiar with SQL Reporting Services, what they are, design, and installation. For more info about this subject, click here. You should have SQL Reporting Services 2005 already installed. Visual Studio 2005 with SQL Server Reporting Services Report Templates installed. Compile the Custom Data Source Extension After loading the source code, you will need to reference the \"Reporting Services Interfaces\". In my case, it is located in: C:\\Program Files\\Microsoft SQL Server\\90\\SDK\\Assemblies\\Microsoft.ReportingServices.Interfaces.dll; however, this may differ for your installation.\nOnce you have made the reference, you should be able to compile the application.\nInstallation of the Custom Data Source After downloading the source above for the custom data processing extension, you must install it to enable access. The installation process is performed in two steps:\nInstalling and configuring the extension. Configuring extension security. This particular extension is used both by the Reporting Server and within the Visual Studio 2005 Report Designer; both have a different location for configuration, either on the server or your development machine. However both configurations are very similar.\nDevelopment Installation Two configuration files are required to be changed in order for you to be able to see your Custom Data Source from within the development environment. These files typically are held in C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE\\PrivateAssemblies; these files are:\nRSReportDesigner.config RSPreviewPolicy.config Copy your assembly First, you need to copy the Custom Data Source files to the \"PrivateAssemblies\" folder, as this is where they are referenced.\nSetup the configuration file The RSReportDesigner.config holds the reference to the Extension. The following needs to be added to the \u003cData\u003e tag within the \u003cExtension\u003e tag:\nCollapse \u003cExtension Name=\"CUSTOM_DATASOURCE\" Type=\"DataSourceExtension.DataSetConnection, DataSourceExtension\" /\u003e In order for the designer to use the Custom Data Source, you need to add the following to the \u003cDesigner\u003e tag, usually situated just below the \u003cData\u003e tag:\nCollapse \u003cExtension Name=\"CUSTOM_DATASOURCE\" _Type=\"Microsoft.ReportingServices.QueryDesigners.GenericQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u003e You will notice that this time we are pointing to the standard Microsoft Generic Query Designer. This is because we are trying to build a Custom Data Source Extension and not a Query Designer.\nWhat you should end up with is a RSReportDesigner.config file, looking something like this:\nCollapse \u003cConfiguration\u003e \u003cAdd Key=\"SecureConnectionLevel\" Value=\"0\" /\u003e \u003cAdd Key=\"InstanceName\" Value=\"Microsoft.ReportingServices.PreviewServer\" /\u003e \u003cAdd Key=\"SessionCookies\" Value=\"true\" /\u003e \u003cAdd Key=\"SessionTimeoutMinutes\" Value=\"3\" /\u003e \u003cAdd Key=\"PolicyLevel\" Value=\"rspreviewpolicy.config\" /\u003e \u003cAdd Key=\"CacheDataForPreview\" Value=\"true\" /\u003e \u003cExtensions\u003e \u003cRender\u003e \u003cExtension Name=\"XML\" Type=\"Microsoft.ReportingServices.Rendering.XmlDataRenderer.XmlDataReport,Microsoft.ReportingServices.XmlRendering\" /\u003e \u003cExtension Name=\"CSV\" Type=\"Microsoft.ReportingServices.Rendering.CsvRenderer.CsvReport,Microsoft.ReportingServices.CsvRendering\" /\u003e \u003cExtension Name=\"IMAGE\" Type=\"Microsoft.ReportingServices.Rendering.ImageRenderer.ImageReport,Microsoft.ReportingServices.ImageRendering\" /\u003e \u003cExtension Name=\"RGDI\" Type=\"Microsoft.ReportingServices.Rendering.ImageRenderer.RemoteGdiReport,Microsoft.ReportingServices.ImageRendering\" Visible=\"false\" /\u003e \u003cExtension Name=\"PDF\" Type=\"Microsoft.ReportingServices.Rendering.ImageRenderer.PdfReport,Microsoft.ReportingServices.ImageRendering\" /\u003e \u003cExtension Name=\"HTML4.0\" Type=\"Microsoft.ReportingServices.Rendering.HtmlRenderer.Html40RenderingExtension,Microsoft.ReportingServices.HtmlRendering\" Visible=\"false\" /\u003e \u003cExtension Name=\"HTML3.2\" Type=\"Microsoft.ReportingServices.Rendering.HtmlRenderer.Html32RenderingExtension,Microsoft.ReportingServices.HtmlRendering\" Visible=\"false\" /\u003e \u003cExtension Name=\"MHTML\" Type=\"Microsoft.ReportingServices.Rendering.HtmlRenderer.MHtmlRenderingExtension,Microsoft.ReportingServices.HtmlRendering\" /\u003e \u003cExtension Name=\"EXCEL\" Type=\"Microsoft.ReportingServices.Rendering.ExcelRenderer.ExcelRenderer,Microsoft.ReportingServices.ExcelRendering\" /\u003e \u003c/Render\u003e \u003cData\u003e \u003cExtension Name=\"SQL\" Type=\"Microsoft.ReportingServices.DataExtensions.SqlConnectionWrapper,Microsoft.ReportingServices.DataExtensions\" /\u003e \u003cExtension Name=\"OLEDB\" Type=\"Microsoft.ReportingServices.DataExtensions.OleDbConnectionWrapper,Microsoft.ReportingServices.DataExtensions\"/\u003e \u003cExtension Name=\"OLEDB-MD\" Type=\"Microsoft.ReportingServices.DataExtensions.AdoMdConnection,Microsoft.ReportingServices.DataExtensions\"/\u003e \u003cExtension Name=\"ORACLE\" Type=\"Microsoft.ReportingServices.DataExtensions.OracleClientConnectionWrapper,Microsoft.ReportingServices.DataExtensions\"/\u003e \u003cExtension Name=\"ODBC\" Type=\"Microsoft.ReportingServices.DataExtensions.OdbcConnectionWrapper,Microsoft.ReportingServices.DataExtensions\"/\u003e \u003cExtension Name=\"XML\" Type=\"Microsoft.ReportingServices.DataExtensions.XmlDPConnection,Microsoft.ReportingServices.DataExtensions\"/\u003e \u003cExtension Name=\"RS\" Type=\"Microsoft.ReportingServices.DataExtensions.RSDPConnection,Microsoft.ReportingServices.DataExtensions\"/\u003e \u003cExtension Name=\"CUSTOM_DATASOURCE\" Type=\"DataSourceExtension.DataSetConnection, DataSourceExtension\" /\u003e\u003c/Data\u003e \u003cDesigner\u003e \u003cExtension Name=\"SQL\" Type=\"Microsoft.ReportingServices.QueryDesigners.VDTQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u003e \u003cExtension Name=\"OLEDB\" Type=\"Microsoft.ReportingServices.QueryDesigners.VDTQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u003e \u003cExtension Name=\"OLEDB-MD\" Type=\"Microsoft.ReportingServices.QueryDesigners.ASQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u003e \u003cExtension Name=\"ORACLE\" Type=\"Microsoft.ReportingServices.QueryDesigners.VDTQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u003e \u003cExtension Name=\"ODBC\" Type=\"Microsoft.ReportingServices.QueryDesigners.VDTQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u003e \u003cExtension Name=\"XML\" Type=\"Microsoft.ReportingServices.QueryDesigners.GenericQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u003e \u003cExtension Name=\"RS\" Type=\"Microsoft.ReportingServices.QueryDesigners.SMQLQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u003e \u003cExtension Name=\"CUSTOM_DATASOURCE\" Type=\"Microsoft.ReportingServices.QueryDesigners.GenericQueryDesigner,Microsoft.ReportingServices.QueryDesigners\"/\u003e\u003c/Designer\u003e \u003c/Extensions\u003e \u003c/Configuration\u003e Security configuration The security is held in the RSPreviewPolicy.config file, which is in the same folder as the configuration file (RSReportDesigner.config). This file provides the security policy for SQL Server Reporting Services and allows access to your DLL.\nCollapse \u003cCodeGroup class=\"UnionCodeGroup\" version=\"1\" PermissionSetName=\"FullTrust\" Name=\"Customer_DataSource\"Description=\"Code group for my Custom DataSource for data processing extension\"\u003e\u003cIMembershipCondition class=\"UrlMembershipCondition\" version=\"1\" Url=\"C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE\\PrivateAssemblies\\DataSourceExtension.dll\"/\u003e \u003c/CodeGroup\u003e Server Installation To configure the Custom Data Extension on the server where your reports will be running, is a case of following the above, except you'll find the configuration files held in a different location, and depending on the installation, they appear in different places. On my installation file, they are all held in C:\\Program Files\\Microsoft SQL Server\\MSSQL.2\\Reporting Services\\ReportServer\\bin and the configuration files are held inC:\\Program Files\\Microsoft SQL Server\\MSSQL.2\\Reporting Services\\ReportServer, with the names of the configuration files being:\nrsreportserver.config rssrvpolicy.config As this is a server install, you will not need to make or add the \u003cDesigner\u003e tag.\nTesting of the Custom Data Source Extension In order to test the Custom Data Source Extension, you will need to generate either a report or a Shared Data Source that points to the new custom Data Source Extension.\nCreate a new project within Visual Studio 2005, select a \"Business Intelligence Project\", and select the \"Report Server Project Wizard\" from the list of templates. On the new data type list, you should see \"Custom DataSource Extension\". If, however, you don't, but you do see CUSTOM_DATASOURCE, this means that the configuration has not picked up your DataSourceExtension.dll, and you will need to check over the configuration files.\nEnter a connection string, like the following: \"FileName=C:\\bottles.xml\", you'll find this file at the top in the download section. Click next, this will take you to the \"Design a Query\" screen. Enter the following query: \"select * from company\", as shown below:\nClick Next, and then continue until you have finished creating a report. You should now be able to run the report with the new Custom DataSource Extension that you can customise and shape to your own needs.\nPoints of Interest Now that you have it running and working, it is worth going over how to debug the Custom Data Extension. I was not intending to cover this in this article, and will reference you to Microsoft TechNet on Debugging Data Processing Extension Code, as this should provide you with sufficient information on how to setup debugging.\nHistory First release.\n","title":"Implementing a Data Processing Extension","type":"articles"},{"content":"\nSimple connection and Controls to make those PayPal payment easier I created this simple set of controls to make it easier to add PayPal simple buttons, all you need is a PayPal account and the buttons can point to allow you to make payment. Please feel free to test out the BuyNow button in to my account b_avery@yahoo.com, all funds welcome. Currently I am only adding features as and when I need them, but feel free to make comments or requests in the Discussions and Issue Tracker sections Source can be found at CodePlex Other sources worth look at are : Use of the PayPal payment system in ASP.NET http://www.codeproject.com/KB/aspnet/UsePayPalPaymentInASPNET/ ","date":"11 November 2008","externalUrl":null,"permalink":"/simple-paypal/","section":"Articles","summary":"\nSimple connection and Controls to make those PayPal payment easier I created this simple set of controls to make it easier to add PayPal simple buttons, all you need is a PayPal account and the buttons can point to allow you to make payment. Please feel free to test out the BuyNow button in to my account b_avery@yahoo.com, all funds welcome. Currently I am only adding features as and when I need them, but feel free to make comments or requests in the Discussions and Issue Tracker sections Source can be found at CodePlex Other sources worth look at are : Use of the PayPal payment system in ASP.NET http://www.codeproject.com/KB/aspnet/UsePayPalPaymentInASPNET/ ","title":"Simple PayPal","type":"articles"},{"content":" Having a number of SSRS reports is all well and good, but if the end users can not see the reports it is useless, therefore we need to generate a method of viewing the reports via a small application.\nThe Report Viewer application will be built using C# .NET 2.0, and is configurable by the Web Services supplied by Reporting Services. The Reporting Services Web Services is an industry standard way of accessing information via SOAP .\nThe Web Services supplied by Reporting Services provide an interface in the reporting engine to gain access to the reports and the report inner workings.\nBy interfacing to the Reporting Services Web Services we can extract the available reports that have been loaded on to the Reporting Services Server. We can then display a bespoke parameter screen which can capture all that is required before displaying the report.\nWhen the Report Viewer is loaded it will communicate to the Report Server, which is configurable via the application configuration file, to retrieve a list of available reports and folders.\nThe reports and folders can then be displayed within the Report Viewer as a list, upon selecting a folder the Report Viewer will then go in to that folder and return a list of reports and folders. It is important to note that only visible objects will be displayed, any objects that have been set to hidden will not be displayed in the Report Viewer. This allows for ancillary objects, like images and data sources, to be hidden from the end users.\nOnce a report has been selected the parameters for that report are dynamically displayed by the Report Viewer, looking at the parameter list from the Report Server Web Services and generating the required requests.\nOnce all the parameters have been captured the Report Viewer will make a request to the Report Server via HTML to retrieve the report and pass the parameters, this will allow for the Report Viewer to display the report to the user, who can then elect to either print or export the report is they so desire. This code is intended to provide viewer for SQL Reporting Services that uses exclusively the SOAP API for rendering. The Viewer will be embedded as a Custom User Controls fragment into the calling form. 4\nThis document will help you if you are looking for more control over how you can integrate a report and its parameters into the Report Viewer application that may use different authentication methods than Reporting Services, usually if you want something more than what you already find in the ReportViewer web server control. All prompts for parameters are created dynamically and you can easily apply different formatting or even hide some of them.\nUsing Report Viewer\nUsing the Report Viewer is very simple, just supplying the, Report Server WSDL path, the location of the Report Server and if you need to the report folder. Setting up the application configuration file, follows the Microsoft standard for attaching to Web Services, and providing application parameters, an example of an app.config file is listed below\n\u0026lt;add key=\"ReportServer\" value=\"http://172.24.8.170/ReportServer/\" /\u0026gt;\n\u0026lt;add key=\"ReportConfiguration\" value=\"%26rc:Parameters=false\" /\u0026gt;\n\u0026lt;add key=\"ReportURL\" value=\"http://172.24.8.170/ReportServer/Pages/ReportViewer/?{0}%26rs:Command=Render\" /\u0026gt;\n\u0026lt;add key=\"ReportWebReport\" value=\"true\" /\u0026gt;\nExample C# code for using and calling the Report Viewer:\n//Instantiate the object EH.ReportViewer.Reports r = new EH.ReportViewer.Reports();\n//Pass the report folder you wish to start in, if this is not supplied then the root will be used\nr.ReportFolder = \"/Photonet Reports Project\";\n//Load a single form, if you leave this out a collection of forms will be displayed\nreports.ReportName = ReportName;\n//Display the reports\nr.DisplayReports(); Key Points\nI consider the most interesting point to be the way we can rebuild parameter prompts. This opens the door for customizing these prompts, for example, set a Calendar control for a DateTime parameter, hide some report parameters, or provide values behind the scene. !!Known Limitations\nSo far the code does not perform validation. This means that if you submit a blank value for a field that does not accept blank values, the code will not show any validation message.\nThe Parameter form does expand depending on the number of parameters that are supplied in the report, and depending on your screen size the height may extend beyond the size of the screen.\nWhen a parameter is based from a query it currently is not displayed, as this will be an extension to the currently functionality pf the Report Viewer, and it is currently not required for this release of code. Source Code can be found on CodePlex\n","date":"11 November 2008","externalUrl":null,"permalink":"/report-viewer/","section":"Articles","summary":" Having a number of SSRS reports is all well and good, but if the end users can not see the reports it is useless, therefore we need to generate a method of viewing the reports via a small application.\n","title":"Report Viewer","type":"articles"},{"content":"With the release of .Net 3.5 SP1 comes ASP.NET Dynamic Data. Dynamic Data is a great tool to generate an administration website for your data access, enabling you to get at the data in a very simple method.\nNot only is the viewing of the information simple, but also the building of such website could not be any easier.\nHere are a few places you might find interesting:\nASP.NET Dynamic Data Demo\nPutting ASP.NET Dynamic Data into Context\nHanselminutes Podcast 109 – ASP.NET Dynamic Data with Scott Hunter New ASP.NET Dynamic Data Support\n","date":"11 November 2008","externalUrl":null,"permalink":"/dynamic-data/","section":"Articles","summary":"With the release of .Net 3.5 SP1 comes ASP.NET Dynamic Data. Dynamic Data is a great tool to generate an administration website for your data access, enabling you to get at the data in a very simple method.\n","title":"Dynamic Data","type":"articles"},{"content":"I am always after good pod casts to listen to when you are not busy, driving the car or on the train. So I thought I'd start to compile a list of worth listening to Pod Casts\nPods \u0026amp; Blogs – 5 Live from the BBC\nEscape Pod – The Science Fiction Podcast Magazine\nHansel Minutes – Weekly .Net pod cast\n","date":"11 November 2008","externalUrl":null,"permalink":"/pod-casts-on-the-move/","section":"Articles","summary":"I am always after good pod casts to listen to when you are not busy, driving the car or on the train. So I thought I'd start to compile a list of worth listening to Pod Casts\n","title":"Pod Casts on the move","type":"articles"},{"content":"\nNeed to change the membership provider programmatically? string username = \"user\"; string password = \"password\"; MembershipUser membershipUser = Membership.Providers[\"SqlMembershipProviderOther\"].GetUser(username); membershipUser.ChangePassword(membershipUser.ResetPassword(), password); Also worth checking out here ","date":"10 November 2008","externalUrl":null,"permalink":"/changing-membership-provider/","section":"Articles","summary":"\nNeed to change the membership provider programmatically? string username = \"user\"; string password = \"password\"; MembershipUser membershipUser = Membership.Providers[\"SqlMembershipProviderOther\"].GetUser(username); membershipUser.ChangePassword(membershipUser.ResetPassword(), password); Also worth checking out here ","title":"Changing Membership provider","type":"articles"},{"content":"Like Windows Vista, you can perform a number of changes to increase the performance of Visual Studio. First make sure you have the latests Service Pack installed. Under Options, make sure Animation environment tools. If you don’t use the Navigation bar, then turn this off. Make sure Track changes of off. In Options, Text Editor and uncheck Track Changes. Track Active Item in Solution Explorer, remove this, it can be found in Options, Projects and Solutions. (Don’t do this for a VB application) Disable AutoToolboxPopulate, this is found in Options, Windows Forms Designer Disable the Startup screen by selecting Show Empty Environment When loading Visual Studio, disable the splash screen “devenv.exe /nosplash” ","date":"10 November 2008","externalUrl":null,"permalink":"/increase-development-by-increasing-the-speed-of-visual-studio/","section":"Articles","summary":"Like Windows Vista, you can perform a number of changes to increase the performance of Visual Studio. First make sure you have the latests Service Pack installed. Under Options, make sure Animation environment tools. If you don’t use the Navigation bar, then turn this off. Make sure Track changes of off. In Options, Text Editor and uncheck Track Changes. Track Active Item in Solution Explorer, remove this, it can be found in Options, Projects and Solutions. (Don’t do this for a VB application) Disable AutoToolboxPopulate, this is found in Options, Windows Forms Designer Disable the Startup screen by selecting Show Empty Environment When loading Visual Studio, disable the splash screen “devenv.exe /nosplash” ","title":"Increase Development by increasing the speed of Visual Studio","type":"articles"},{"content":" If you are building an application for general release, and would like to build it using .Net 3.5 SP1, it would be nice to know if the end users already have .Net 3.5 SP1.\nWe can safely say that the majority of end users has .Net 2.0, as this is part of the Windows update process.\nCurrently to upgrade to .Net 3.5 SP1 you will need a separate download,which is not a small download.\nHelp is at hand as Microsoft will be shipping the .Net 3.5 SP1 through Windows Update, for all users that have .Net2.0 installed, and Windows update enabled, this will be available in January 2009.\nThis does not apply to Visual Studio 2008, as you will still require a separate download.\n[more] ","date":"5 November 2008","externalUrl":null,"permalink":"/when-will-net-3-5-sp1-be-available-on-all-machines/","section":"Articles","summary":" If you are building an application for general release, and would like to build it using .Net 3.5 SP1, it would be nice to know if the end users already have .Net 3.5 SP1.\n","title":"When will .Net 3.5 sp1 be available on all machines?","type":"articles"},{"content":"What do you need to get SVN to working within Visual Studio 2008?\nYou should only need AnkhSVN, as this is an AddIn for Visual Studio 2008. But it is worth getting Torroise SVN to allow for access to SVN via the file manager.\nIf you need to run SVN on your machine to hold the safe then you’ll need SubVersion\nOnce you have SVN installed it is always worth adding a global ignore pattern to TortoiseSVN, he is one that Jonathan Merrifield provided me with. Put this in TortoiseSVN -\u0026gt; Settings -\u0026gt; Global ignore pattern\n*.o *.lo .la ## .*.rej .rej .~ ~ .# .DS_Store thumbs.db Thumbs.db *.bak *.class *.exe *.dll *.mine *.obj *.ncb *.lib *.log *.idb *.pdb *.ilk .msi .res *.pch *.suo *.exp .~ .~ ~. cvs CVS .CVS .cvs release Release debug Debug ignore Ignore bin Bin obj Obj *.csproj.user *.user A nice article worth having a look at is by Alexey Smirnov, Version Control, article below\nVersion Control Getting Started with AnkhSVN and Subversion By Alexey Smirnov\nThere are a few version control solutions for ASP.NET out there on the market. One of them is a new version of AnkhSVN. AnkhSVN 2.0 is a free Subversion client, implemented as a package for Microsoft Visual Studio 2005 and 2008. It provides an interface to perform the most common revision control operations directly from inside the VS.NET IDE.\nThis article provides an introduction to AnkhSVN by describing how the product works and explaining its main operations.\nAs mentioned above, AnkhSVN is a Subversion client; in other words, an interface between Subversion, a free open-source version control system, and Visual Studio .NET. On its own, Subversion allows one to track and store code changes, collaborate, and share project files. All information about project files is saved to a repository, a simple directory structure. To create and manage a repository you would need to install Subversion or one of several other third-party client applications. For this purpose, this article used TortoiseSVN, a standalone Subversion client.\nThere are many good reasons for AnkhSVN and TortoiseSVN cooperation. While TortoiseSVN has all the necessary commands to work with Subversion and can be used as a standalone version control tool, AnkhSVN focuses on automating common tasks for Visual Studio developers and integrating to the IDE. Used together, both tools can provide everything needed to make the development process quick and easy.\nThe most recent versions of AnkhSVN and TortoiseSVN can be found on their official Web sites: http://www.ankhsvn.com and http://www.tortoisesvn.net.\nOnce AnkhSVN and TortoiseSVN have been downloaded and installed, it is required to create the initial repository. To accomplish this, first create a new folder. TortoiseSVN extends Windows Explorer and all commands are available from its context menu. Right-click on the new folder and access the TortoiseSVN menu. Select the Create Repository Here option. Start Visual Studio and make sure AnkhSVN is the active source control provider. Open Tools | Options | Source Control and check that AnkhSVN is already selected.\nOpen a project in VS.NET. From File Menu | Subversion | Add add the solution to Subversion. In the Add to Subversion dialog box add the Repository URL created in the previous step. For a directory located at D:\\SvnRepos the URL will be file:///D:/SvnRepos/.\nAfter that you’ll see in Solution Explorer a blue plus sign (+) next to each file. This means your files are ready to work with Subversion. To add files in the repository, open the context menu in Solution Explorer and click Add, then click Commit. You’ll see green checkmarks alongside items in Solution Explorer. Now your project is under version control and the initial version of the project is saved in the repository.\nAnkhSVN adds to Visual Studio a new Pending Changes window to show all changes in a single location rather than having to navigate through Windows Explorer or even Solution Explorer. Once you start to make changes, you’ll see modified items added to the Pending Changes window. This window is accessible through View | Show Pending Changes.\nIf a project has been modified and new revisions were added in a repository, you can restore the revisions by using Update and View History in the context menu of Solution Explorer. To restore the previous version, go to Update | Revision | Previous. To get back to the specific revision, open View History and find the number of the revision you want to get back. Then open Update and specify the number to get the right revision.\nUpdate and View History can be applied concurrently to multiple files. To restore a single file you may use Revert to get the revision menu from Solution Explorer.\nYou’ll get a more advanced interface to work with the repository in TortoiseSVN. Go to Windows Explorer. In the context menu find TortoiseSVN | Update to revision, where you can choose which revision has to be restored in the project directory.\nOne of the features of a version control system is the ability to isolate changes onto a separate line of development. This line is known as a branch. Branches are often used to try new features without disturbing the main line of development with compiler errors and bugs. As soon as the new feature is stable enough, the development branch is merged back in to the main branch (trunk). Another feature of a version control system is the ability to mark particular revisions (e.g., a release version) so at any time you can recreate a certain build or environment. This process is known as tagging.\nSubversion combines these two processes into one. Create Branch/Tags is available in TortoiseSVN through the context menu Branch/Tags. Specify the URL for the new branch; for example, “project_url/1.0” where “1.0” will be the name of the branch. Use the Switch working copy to new branch/tag checkbox if you want your working copy to be switched to the newly created branch.\nAfter that you can work on the project as usual and when you need to return the whole project back to version 1.0, use the Update to revision command.\nConclusion The new release of AnkhSVN is fast and stable compared to the earlier versions — and a good alternative to other source control solutions for ASP.NET developers. This article covered typically used commands of AnkhSVN and explained main steps to start working with AnkhSVN and Subversion. More information about Subversion and other third-party clients can be found at http://subversion.tigris.org.\nAlexey Smirnov is an IT consultant and a Microsoft MVP. You can reach him at mailto:alexey.smirnov@gmail.com.\n","date":"4 November 2008","externalUrl":null,"permalink":"/what-do-you-need-to-get-subversion-working-in-visual-studio-2008/","section":"Articles","summary":"What do you need to get SVN to working within Visual Studio 2008?\nYou should only need AnkhSVN, as this is an AddIn for Visual Studio 2008. But it is worth getting Torroise SVN to allow for access to SVN via the file manager.\n","title":"What do you need to get SubVersion working in Visual Studio 2008","type":"articles"},{"content":" Make sure your code is styled correctly Code Style Enforcer is a DXCore plug-in for Visual Studio 2005 / 2008 that checks the code against a configurable code standard and best practices. It is developed for C#, but some of the rules will also work for VB .NET, though not tested. The code standard is currently configurable with the following rules…[more]\nOf course you are going to need standards to work to, The IDesign C# Coding Standard, for development guidelines and best practices.\n","date":"3 November 2008","externalUrl":null,"permalink":"/code-style-enforcer/","section":"Articles","summary":" Make sure your code is styled correctly Code Style Enforcer is a DXCore plug-in for Visual Studio 2005 / 2008 that checks the code against a configurable code standard and best practices. It is developed for C#, but some of the rules will also work for VB .NET, though not tested. The code standard is currently configurable with the following rules…[more]\n","title":"Code Style Enforcer","type":"articles"},{"content":"Just ran in to an issue of security when having many web applications. I needed all the web application to use the same security access, after a little research I found that Client Application Services in VS2008 works a treat, as it has been written to handle security in the cloud.\nI found a few good articles on the subject\nClient Application Services with Visual Studio 2008\nImplementing Application Security with Client Application Services in VS2008 Best of all I just love how it handles if your remote server is off line or not available\nConnectivityStatus.IsOffline = true; To get this working in your web application you will need to make a few changes to the Web.Config, and then point the serviceUri to your service\n\u0026lt;sectionGroup name=\"applicationSettings\" type=\"System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"\u0026gt;\n\u0026lt;section name=\"testing_Security.Properties.Settings\" type=\"System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" requirePermission=\"false\" /\u0026gt;\n\u0026lt;/sectionGroup\u0026gt;\n\u0026lt;appSettings\u0026gt;\n\u0026lt;add key=\"ClientSettingsProvider.ServiceUri\" value=\"http://localhost:55666/AppServices/Profile_JSON_AppService.axd\" /\u0026gt;\n\u0026lt;/appSettings\u0026gt;\n\u0026lt;membership defaultProvider=\"ClientAuthenticationMembershipProvider\"\u0026gt;\n\u0026lt;providers\u0026gt;\n\u0026lt;add name=\"ClientAuthenticationMembershipProvider\" type=\"System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" serviceUri=\"http://localhost:55666/AppServices/Authentication_JSON_AppService.axd\" /\u0026gt;\n\u0026lt;/providers\u0026gt;\n\u0026lt;/membership\u0026gt;\n\u0026lt;roleManager defaultProvider=\"ClientRoleProvider\" enabled=\"true\"\u0026gt;\n\u0026lt;providers\u0026gt;\n\u0026lt;add name=\"ClientRoleProvider\" type=\"System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" serviceUri=\"http://localhost:55666/AppServices/Role_JSON_AppService.axd\" cacheTimeout=\"86400\" /\u0026gt;\n\u0026lt;/providers\u0026gt;\n\u0026lt;/roleManager\u0026gt; Web.config (8.75 kb)\n","date":"3 November 2008","externalUrl":null,"permalink":"/client-application-services-in-vs2008/","section":"Articles","summary":"Just ran in to an issue of security when having many web applications. I needed all the web application to use the same security access, after a little research I found that Client Application Services in VS2008 works a treat, as it has been written to handle security in the cloud.\n","title":"Client Application Services in VS2008","type":"articles"},{"content":"Can't read what is on the screen, or need to highlight something to someone, you don't have to be running presentation to have this tool.\nZoomIt is screen zoom and annotation tool for technical presentations that include application demonstrations. ZoomIt runs unobtrusively in the tray and activates with customizable hotkeys to zoom in on an area of the screen, move around while zoomed, and draw on the zoomed image. I wrote ZoomIt to fit my specific needs and use it in all my presentations.\nZoomIt works on all versions of Windows and you can use pen input for ZoomIt drawing on tablet PCs.\nZoom It ","date":"1 November 2008","externalUrl":null,"permalink":"/zoomit/","section":"Articles","summary":"Can't read what is on the screen, or need to highlight something to someone, you don't have to be running presentation to have this tool.\nZoomIt is screen zoom and annotation tool for technical presentations that include application demonstrations. ZoomIt runs unobtrusively in the tray and activates with customizable hotkeys to zoom in on an area of the screen, move around while zoomed, and draw on the zoomed image. I wrote ZoomIt to fit my specific needs and use it in all my presentations.\n","title":"ZoomIt","type":"articles"},{"content":"Here is a list of what is new in .NET 3.5 SP1 and what is to come in .NET 4, also this is a nice example of deep zoom, just zoom in to what you would like to see.\nPDC2008-NETFX4.pdf (3.22 mb)\n","date":"31 October 2008","externalUrl":null,"permalink":"/net-framework-3-5-sp1-and-4-0-poster/","section":"Articles","summary":"Here is a list of what is new in .NET 3.5 SP1 and what is to come in .NET 4, also this is a nice example of deep zoom, just zoom in to what you would like to see.\n","title":".NET Framework 3.5 SP1 and 4.0 Poster","type":"articles"},{"content":"I wrote this small POC, with a little help from samples around the Internet, to retrieve a custom configuration from the application config file (such as web.config)\nIt uses the Microsoft classes ConfigurationSection, ConfigurationElementCollection, and ConfigurationElement\nCustomerConfiguration.zip (3.39 kb)\n","date":"31 October 2008","externalUrl":null,"permalink":"/app-config-custom-configuration/","section":"Articles","summary":"I wrote this small POC, with a little help from samples around the Internet, to retrieve a custom configuration from the application config file (such as web.config)\nIt uses the Microsoft classes ConfigurationSection, ConfigurationElementCollection, and ConfigurationElement\n","title":"App.Config Custom Configuration","type":"articles"},{"content":"Are you developing using LINQ to SQL, and like all good technologies you just want to keep using them, well it looks like Microsoft will be pulling the plug on LINQ to SQL, over the fact the LINQ to Entities will continue forwards in future releases.\nUpdate on LINQ to SQL and LINQ to Entities Roadmap\nMicrosoft Says LINQ to SQL Not Dead\n","date":"31 October 2008","externalUrl":null,"permalink":"/is-linq-to-sql-about-to-be-killed-off/","section":"Articles","summary":"Are you developing using LINQ to SQL, and like all good technologies you just want to keep using them, well it looks like Microsoft will be pulling the plug on LINQ to SQL, over the fact the LINQ to Entities will continue forwards in future releases.\n","title":"Is LINQ to SQL about to be killed off?","type":"articles"},{"content":"I found this very good examples of LINQ samples, I can’t remember where I got it from, so I have upload to my Blog for safe keeping. LINQ Samples.zip (4.27 mb)\nI found another LINQ samples which include\nLINQ to Objects LINQ to SQL LINQ to XML LINQ to XML Part II LINQ to DataSet LINQ to Entities I got it from Charlie Calvert’s Community Blog, and I have placed them here on my Blog for safe keeping. MarchCtpSamples-v04.zip (3.78 mb)\nSome more worth looking at:\nC# 101 LINQ Samples VB.NET 101 LINQ Samples\n","date":"28 October 2008","externalUrl":null,"permalink":"/linq-samples/","section":"Articles","summary":"I found this very good examples of LINQ samples, I can’t remember where I got it from, so I have upload to my Blog for safe keeping. LINQ Samples.zip (4.27 mb)\nI found another LINQ samples which include\nLINQ to Objects LINQ to SQL LINQ to XML LINQ to XML Part II LINQ to DataSet LINQ to Entities I got it from Charlie Calvert’s Community Blog, and I have placed them here on my Blog for safe keeping. MarchCtpSamples-v04.zip (3.78 mb)\n","title":"LINQ Samples","type":"articles"},{"content":"After 8 years, Microsoft are rebranding .Net, and here is the new Logo\nFor more details click here ","date":"26 October 2008","externalUrl":null,"permalink":"/new-net-logo/","section":"Articles","summary":"After 8 years, Microsoft are rebranding .Net, and here is the new Logo\nFor more details click here ","title":"New .Net Logo","type":"articles"},{"content":"Registration is now open\nhttp://www.developerday.co.uk/ddd/default.asp Don't forget it sold out within 24 hours last year\n","date":"22 October 2008","externalUrl":null,"permalink":"/ddd7-registration-is-open/","section":"Articles","summary":"Registration is now open\nhttp://www.developerday.co.uk/ddd/default.asp Don't forget it sold out within 24 hours last year\n","title":"DDD7 Registration Is Open","type":"articles"},{"content":"After using the BlogEngine Newsletter, I noticed that it was not easy to unsubscribe from the newsletter, so I went to task and produced an enhanced Newsletter so you can unsubscribe from the newletter from the incoming email.\nAs a result I also increased what is being sent on the e-mail, to provide more information for the subscriber.\nOne other feature I added was that is a post is saved but in an unpublished state an e-mail is sent to the administrator informing them of a new unpublished post. Upzip this attached file and place the folder in the widgets directory of the application. Be sure to over right or replace the existing Newsletter otherwise people will receive two emails for each post.\nNewsletter.zip (4.23 kb)\n","date":"21 October 2008","externalUrl":null,"permalink":"/newsletter-enhancements/","section":"Articles","summary":"After using the BlogEngine Newsletter, I noticed that it was not easy to unsubscribe from the newsletter, so I went to task and produced an enhanced Newsletter so you can unsubscribe from the newletter from the incoming email.\n","title":"Newsletter Enhancements","type":"articles"},{"content":"Microsoft have release for the Beta version of MVC (Model View Control), it has been around in the community preview release for some time and now it is in it’s final stages before being fully released.\nASP.NET MVC Scott Gu’s Release Notes\nFree ASP.NET MVC “NerdDinner”\nScott Hanselmann on MVC\nYou need to make sure you are running Visual Studio 2008 before you even think about using MVC.\nIt’s now time to take MVC as a serious method of development, as it won’t be very long before the final offical release is shipped. ","date":"17 October 2008","externalUrl":null,"permalink":"/asp-net-mvc-beta-released/","section":"Articles","summary":"Microsoft have release for the Beta version of MVC (Model View Control), it has been around in the community preview release for some time and now it is in it’s final stages before being fully released.\n","title":"ASP.NET MVC Beta Released","type":"articles"},{"content":"Okay, I've been pulling my hair out for the last three days as Remote Desktop is running very slow and timing out on my Vista machine, calls to the host provided and BT have not solved the issue.\nFound out this morning that remote desktop works fine on my XP machine, so it must be something Vista is doing. After a quick search on the net I found this article, and it worked, now running Remote Desktop at the right speed.\nhttp://blog.tmcnet.com/blog/tom-keating/microsoft/remote-desktop-slow-problem-solved.asp In short\nHere is what you need to do if you have the same issue:\n– Run a command prompt (cmd.exe) as an Administrator\n– Type: netsh interface tcp set global autotuninglevel=disabled\nIf you want to to re-enable it:\n– Type: netsh interface tcp set global autotuninglevel=normal\nIn some cases you may need to use this command in addition to the above, but I didn't have to:\n– Type: netsh interface tcp set global rss=disabled\n","date":"16 October 2008","externalUrl":null,"permalink":"/remote-desktop-running-slow-on-vista/","section":"Articles","summary":"Okay, I've been pulling my hair out for the last three days as Remote Desktop is running very slow and timing out on my Vista machine, calls to the host provided and BT have not solved the issue.\n","title":"Remote Desktop running slow on Vista","type":"articles"},{"content":"\nI know Chrome is only in Beta, and so far it has been very reliable, but for some reason today, for no reason it crashed on me, not doing anything special just surfing the web\n","date":"14 October 2008","externalUrl":null,"permalink":"/chrome-crashing/","section":"Articles","summary":"\nI know Chrome is only in Beta, and so far it has been very reliable, but for some reason today, for no reason it crashed on me, not doing anything special just surfing the web\n","title":"Chrome Crashing","type":"articles"},{"content":"I’ve created a simple iPhone Theme for the BlogEngine, using both Style Sheet, with a few tweeks, from the iUI Project Members, and a simple javaScript accordian by dezinerfolio.com\nJust places iPhone folder in the Themes directory of the BlogEngine. iPhone.zip (29.91 kb)\nThis is the first pass at an iPhone theme, there are still features I’d like to put in, such as Previous and Next links, Pages, Categories, but not had time to do that at the moment. Further information on CSS for the iPhone can be found here\n","date":"13 October 2008","externalUrl":null,"permalink":"/iphone-theme-for-blogengine/","section":"Articles","summary":"I’ve created a simple iPhone Theme for the BlogEngine, using both Style Sheet, with a few tweeks, from the iUI Project Members, and a simple javaScript accordian by dezinerfolio.com\nJust places iPhone folder in the Themes directory of the BlogEngine. ","title":"iPhone Theme for BlogEngine","type":"articles"},{"content":"Wondering if I was running slow today, but no it's not my connection as look what I am running at today ","date":"13 October 2008","externalUrl":null,"permalink":"/connection-speed/","section":"Articles","summary":"Wondering if I was running slow today, but no it's not my connection as look what I am running at today ","title":"Connection Speed","type":"articles"},{"content":"Ever need access to a free Project Manager Gantt Chart application, well I found one today\nGantt Project GanttProject is a free and easy to use Gantt chart based project scheduling and management tool. Our major features include:\nTask hierarchy and dependencies\tGantt chart\tResource load chart\tGeneration of PERT chart\tPDF and HTML reports\tMS Project import/export\tWebDAV based groupwork It's simple to use and very easy, who need Microsoft Project? ","date":"12 October 2008","externalUrl":null,"permalink":"/free-project-management-gantt-project/","section":"Articles","summary":"Ever need access to a free Project Manager Gantt Chart application, well I found one today\nGantt Project GanttProject is a free and easy to use Gantt chart based project scheduling and management tool. Our major features include:\n","title":"Free Project Management Gantt Project","type":"articles"},{"content":"As a developer how often do you say to someone that some development is DONE?\nTo you as the developer, in your head, you have covered everything you need to, well you think you have, so it is DONE. What would the Project Manager say to your work, would it be Done? But worst of all what would the end users say, what is done to them?\nAll three DONE’s above is totally different\nDeveloper DONE: “Done all I can do to make it work and I think it is all working as per the requirements.”\nProject Manager DONE: “We have unit tested, and everything fits the requirements.” Users DONE: “I have an application that works!”\nSo to help the process along here are a few things that the developers need to consider before saying anything is done.\nBrowser Validation Does the Web application working in all Browsers, not forgetting how much time you need to spend developing a web application\nRemember to test in IE6, IE7 \u0026amp; IE8, not forgetting Firefox, Safari, and Chrome, and what about those mobiles? Who is the end user and what will they be using?\nMaximum Characters\nWill the application break if the number of characters goes over what the database can handle for that field?\nResource Files\nAlways remember the text you type in will be changed, you can count on it, so make sure everything is held in the resource file?\nUnit Testing\nOkay, stop laughing, when do you have time to write unit testing in your application? Or more to the point if you application is not running using MVC the user interface is going to be a bugger to test.\nEnvironment Validation\nDon’t just presume that the configuration file is going to contain the correct information, perform validation check on start up to ensure that you have all the information you need to get the application going. Otherwise when it goes off to production you can bet that those operators will change the configuration file and things will start to fall over. Sanity Check Just before you tell your project manager you are DONE, just get one of your colleagues to try out your code just in case you may have missed something.\nWhat does the Enter Key Do?\nCheck and recheck to see what happens when you press the Enter Key on each page, as developers we might miss the Enter key, but you’ll find the most end users will us the Enter key then they are Done on that page.\nReusability\nHas the code been written so it can be reused at a later stage? You don’t want to always have to reinvent the wheel, when you already have one made. Comments\nAs a rule of thumb I always have the warning message set within Visual Studio letting me know if I have missed out any comments. Also a little tool worth getting is the Ghost Doc by Roland Weigelt, as this will save you so much time.\nMarkup Validation Check to make sure all your Markup is validated, this is quite simple, just run your website at http://validator.w3.org/ Sign off\nRelease to ownership of your code, get someone to take responsibility of the next phase, get someone to sign off your code. These are only a few things to consider when you think you are DONE, as a rule of thumb I never tell anyone I am done, I wait until someone else says it is done.\nAnother good source for producing High Quality Website can be found here\n","date":"12 October 2008","externalUrl":null,"permalink":"/remember-remember-to-finish-off-when-is-done/","section":"Articles","summary":"As a developer how often do you say to someone that some development is DONE?\nTo you as the developer, in your head, you have covered everything you need to, well you think you have, so it is DONE. What would the Project Manager say to your work, would it be Done? But worst of all what would the end users say, what is done to them?\n","title":"Remember, Remember to finish off – When is DONE?","type":"articles"},{"content":"I don't know about you, but when I am looking after a website I like to know if something has gone wrong on the website, mainly so you can fix it as soon as it happens and resolve the issue before the user of the website gets feed up and goes somewhere else.\nWithin ASP.NET you can configure the Global.ASAX Application_Error to capture an exceptions that are happening on you web site, so why not catch the exception and then e-mail it to the administrator of the website.\nThe example below works well with BlogEngine, as it uses the prebuilt settings and more importantly the Async sending of emails.\nvoid Application_Error(object sender, EventArgs e) { Exception objErr = Server.GetLastError().GetBaseException(); string err = \"\u0026lt;b\u0026gt;Error Caught in Application_Error event\u0026lt;/b\u0026gt;\u0026lt;hr\u0026gt;\u0026lt;br\u0026gt;\" + \"\u0026lt;br\u0026gt;\u0026lt;b\u0026gt;Error in: \u0026lt;/b\u0026gt;\" + Request.Url.ToString() + \"\u0026lt;br\u0026gt;\u0026lt;b\u0026gt;Error Message: \u0026lt;/b\u0026gt;\" + objErr.Message.ToString() + \"\u0026lt;br\u0026gt;\u0026lt;b\u0026gt;Stack Trace:\u0026lt;/b\u0026gt;\u0026lt;br\u0026gt;\" + objErr.StackTrace.ToString(); System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(); string from = BlogSettings.Instance.Email; mail.To.Add(BlogSettings.Instance.Email); mail.From = new System.Net.Mail.MailAddress(from, from); mail.Subject = String.Format(\"Error in the Site - {0} Error\", BlogSettings.Instance.Name); mail.Body += String.Format(\"{0}\u0026lt;br/\u0026gt;\u0026lt;br/\u0026gt;\u0026lt;a href='{1}'\u0026gt;{1}\u0026lt;/a\u0026gt;\u0026lt;br/\u0026gt;\u0026lt;br/\u0026gt;\", System.DateTime.Now.ToString(), Request.Url.ToString()); mail.Body += \"\u0026lt;b\u0026gt;Error Caught in Application_Error event\u0026lt;/b\u0026gt;\u0026lt;hr\u0026gt;\u0026lt;br\u0026gt;\" + \"\u0026lt;br\u0026gt;\u0026lt;b\u0026gt;Error in: \u0026lt;/b\u0026gt;\" + Request.Url.ToString() + \"\u0026lt;br\u0026gt;\u0026lt;b\u0026gt;Error Message: \u0026lt;/b\u0026gt;\" + objErr.Message.ToString() + \"\u0026lt;br\u0026gt;\u0026lt;b\u0026gt;Stack Trace:\u0026lt;/b\u0026gt;\u0026lt;br\u0026gt;\" + objErr.StackTrace.ToString(); mail.Body += \"Server Variables\u0026lt;br/\u0026gt;\u0026lt;br/\u0026gt;\"; foreach (string x in Request.ServerVariables) { mail.Body += x + \" - \" + Request.ServerVariables[x] + \"\u0026lt;br/\u0026gt;\"; } Utils.SendMailMessageAsync(mail); } ","date":"9 October 2008","externalUrl":null,"permalink":"/knowing-when-something-has-gone-wrong/","section":"Articles","summary":"I don't know about you, but when I am looking after a website I like to know if something has gone wrong on the website, mainly so you can fix it as soon as it happens and resolve the issue before the user of the website gets feed up and goes somewhere else.\n","title":"Knowing when something has gone wrong","type":"articles"},{"content":" With the release of .NET FX SP3.5 SP1, comes a bug in the Compare Contract, so watch out when you are coding for the IComparable interface.\nFull details can be found on the Microsoft BCL Team Blog.\nJust as a test I have also built the test application and it does what it says on the tin.\nThe Compare Contract.zip (5.92 kb) (Source is in VS 2008)\n","date":"7 October 2008","externalUrl":null,"permalink":"/the-compare-contract/","section":"Articles","summary":" With the release of .NET FX SP3.5 SP1, comes a bug in the Compare Contract, so watch out when you are coding for the IComparable interface.\nFull details can be found on the Microsoft BCL Team Blog.\n","title":"The Compare Contract","type":"articles"},{"content":"\n","date":"5 October 2008","externalUrl":null,"permalink":"/time-breakdown-of-modern-web-design/","section":"Articles","summary":"\n","title":"Time Breakdown of Modern Web Design","type":"articles"},{"content":"For sometime now I have been using Microsoft Virtual Server to perform testing, it's easy to rebuild and easy to configure.\nI found this useful article from Microsoft on Test Run: Configuration Testing with Virtual Server\n","date":"1 October 2008","externalUrl":null,"permalink":"/testing-using-virtual-server/","section":"Articles","summary":"For sometime now I have been using Microsoft Virtual Server to perform testing, it's easy to rebuild and easy to configure.\nI found this useful article from Microsoft on Test Run: Configuration Testing with Virtual Server\n","title":"Testing using Virtual Server","type":"articles"},{"content":"\nMicrosoft has have release jQuery with all versions of Micrsoft Visual Studio from here on in. With the added support for Intellisense within Visual Studio. Check here for the official details: jQuery and Microsoft jQuery, Microsoft, and Nokia For more information on jQuery check out the offical website Example of jQuery Selector All sounds very exciting. ","date":"30 September 2008","externalUrl":null,"permalink":"/jquery-is-here/","section":"Articles","summary":"\nMicrosoft has have release jQuery with all versions of Micrsoft Visual Studio from here on in. With the added support for Intellisense within Visual Studio. Check here for the official details: jQuery and Microsoft jQuery, Microsoft, and Nokia For more information on jQuery check out the offical website Example of jQuery Selector All sounds very exciting. ","title":"jQuery is here","type":"articles"},{"content":"One thing I have found frustrating about the BlogEngine, when you are developing is I have to go on the the server to recycle the application pool if I need to refresh the object loaded in memory.\nIn addition I wanted a way to find out how may posts, pages and files the BlogEngine held in the application. Also find out the amout of hard disc space they used would be useful.\nSo I went ahead and wrote a Maintenance section Installation is quite simple copy the admin/Maintenance folder in to the admin/maintenance folder.\nAmmend the web.sitemap to include the maintenance\n\u0026lt;siteMapNode url=\"~/admin/Pages/Maintenance/\" title=\"Maintenance\" description=\"\" roles=\"administrators\"/\u0026gt;\nWhen you login as an administrator you will find the maintenance section appear.\nmaintenance.zip (3.83 kb)\n","date":"28 September 2008","externalUrl":null,"permalink":"/blogengine-maintenance/","section":"Articles","summary":"One thing I have found frustrating about the BlogEngine, when you are developing is I have to go on the the server to recycle the application pool if I need to refresh the object loaded in memory.\n","title":"BlogEngine Maintenance","type":"articles"},{"content":"\nWhat is next after Web 2.0? It's got to be Web 3.0 but what is it? Officially it is Semantic Web. The semantic web is relatively unknown to most people and some of the technologies are very complex to understand. Technologies or formats such as FOAF, APML, SIOC, XFN tags and microformats are some of the building blocks of the social aspects of the semantic web. They are used to create cross-site profiles of people and also represent relationships between them. XFN and microformats are somewhat easy to start using, but FOAF, APML and SIOC are a different story. As time goes on I will try to explain each format and how it can be implemented. ","date":"26 September 2008","externalUrl":null,"permalink":"/web-3-0/","section":"Articles","summary":"\nWhat is next after Web 2.0? It's got to be Web 3.0 but what is it? Officially it is Semantic Web. The semantic web is relatively unknown to most people and some of the technologies are very complex to understand. Technologies or formats such as FOAF, APML, SIOC, XFN tags and microformats are some of the building blocks of the social aspects of the semantic web. They are used to create cross-site profiles of people and also represent relationships between them. XFN and microformats are somewhat easy to start using, but FOAF, APML and SIOC are a different story. As time goes on I will try to explain each format and how it can be implemented. ","title":"Web 3.0","type":"articles"},{"content":"Maybe you have already encountered the strange behavior that it takes much longer to copy large files in Windows Vista than in Windows XP. You thought that the change from XP to Vista would at least be not a disadvantage speed wise but Vista somehow seems to have a problem copying large files. This happens especially with mapped drives but it could also be that you witness network disconnects. The problem is caused by a new feature called Auto Tuning which is by default enabled in Microsoft Windows Vista. What Auto Tuning does is that it reacts on changes in the network by tuning the receive windows size. The solution would be of course to disable Auto Tuning in Vista. Some users reported that disabling Auto Tuning had a positive effect on their ability to connect to services such as Windows Live Messenger which did not work before. To disable Auto Tuning and speed up the copy process and avoid timeouts and disconnects do the following: Open a command prompt and type the following: netsh int tcp set global autotuninglevel=disabled To turn it on again: netsh int tcp set global autotuninglevel=normal Cancel some of Windows Vista Effects\nDisabling some of Windows Vista’s Visual effect will make your Video Card and CPU very grateful. Do the following: 1. Open Control Panel.\n2. Click on ‘System and Maintenance’.\n3. Click “Performance Information and Tools”.\n4. Click “Adjust Visual Effects”.\nuncheck everything but : Show shadows under menus Show shadows under mouse pointer Show translucent selection rectangle Show windows content while dragging Smooth edges of screen fonts Use drop shadows for icons labels on the desktop Use visual styles on windows and buttons Remove Tablet Feature If your computer is not a Tablet Computer (most odds) go to Control Panel –\u0026gt; add/Remove and select remove system components uncheck Tablet PC since you don’t have one… For more advanced users you can change the Tablet option in the Services. If you have time to spare then you can watch the Windows Vista Performance Round Table If you are serious about performance, you can also type out Microsoft Xperf, just make sure you read the manual first. ","date":"26 September 2008","externalUrl":null,"permalink":"/speed-up-the-copy-process-on-windows-vista/","section":"Articles","summary":"Maybe you have already encountered the strange behavior that it takes much longer to copy large files in Windows Vista than in Windows XP. You thought that the change from XP to Vista would at least be not a disadvantage speed wise but Vista somehow seems to have a problem copying large files. This happens especially with mapped drives but it could also be that you witness network disconnects. The problem is caused by a new feature called Auto Tuning which is by default enabled in Microsoft Windows Vista. What Auto Tuning does is that it reacts on changes in the network by tuning the receive windows size. The solution would be of course to disable Auto Tuning in Vista. Some users reported that disabling Auto Tuning had a positive effect on their ability to connect to services such as Windows Live Messenger which did not work before. To disable Auto Tuning and speed up the copy process and avoid timeouts and disconnects do the following: Open a command prompt and type the following: netsh int tcp set global autotuninglevel=disabled To turn it on again: netsh int tcp set global autotuninglevel=normal Cancel some of Windows Vista Effects\nDisabling some of Windows Vista’s Visual effect will make your Video Card and CPU very grateful. Do the following: 1. Open Control Panel.\n2. Click on ‘System and Maintenance’.\n3. Click “Performance Information and Tools”.\n4. Click “Adjust Visual Effects”.\n","title":"Speed up the Copy process on Windows Vista","type":"articles"},{"content":"\nI've come across the situation on a number of occasions when coding where I've wanted to convert from a string to an enum.\nHere is one of those methods that you can never find when you're looking for it, but once discovered it seems blindingly obvious:\nobject Enum.Parse(System.Type enumType, string value, bool ignoreCase);\nSo you can write the following kind of code:\nenum Colour\n{\nRed,\nGreen,\nBlue\n}\n// …\nColour c = (Colour) Enum.Parse(typeof(Colour), \"Red\", true);\nConsole.WriteLine(\"Colour Value: {0}\", c.ToString());\n// Picking an invalid colour throws an ArgumentException. To\n// avoid this, call Enum.IsDefined() first, as follows:\nstring nonColour = \"Polkadot\";\nif (Enum.IsDefined(typeof(Colour), nonColour))\nc = (Colour) Enum.Parse(typeof(Colour), nonColour, true);\nelse\nMessageBox.Show(\"Uh oh!\");\nFootnote: interestingly, whilst writing this up I noticed that Enum.IsDefined() doesn’t offer the ignoreCase parameter. If you don’t know whether the casing is right, it seems the only way to do the conversion is using the Parse method and catching the ArgumentException. That's not ideal, since it runs a lot slower. I wonder if this is a loophole in the design?\n","date":"25 September 2008","externalUrl":null,"permalink":"/how-do-you-convert-a-string-into-an-enum/","section":"Articles","summary":"\nI've come across the situation on a number of occasions when coding where I've wanted to convert from a string to an enum.\n","title":"How do you convert a string into an enum?","type":"articles"},{"content":"\nI’m always searching the internet for DateTime formats, so I’ve placed them in my Blog so I’ll also know where I can find them\nDateTime Format Specifiers\nBelow lists the valid format specifiers supported by the Format method on theDateTime type (see System.IFormattable).\nDateTime Format Specifiers\nSpecifier String Result d MM/dd/yyyy D dddd, MMMM dd, yyyy f dddd, MMMM dd, yyyy HH:mm F dddd, MMMM dd, yyyy HH:mm:ss g MM/dd/yyyy HH:mm G MM/dd/yyyy HH:mm:ss m, M MMMM dd r, R Ddd, dd MMM yyyy HH’:’mm’:’ss ‘GMT’ s yyyy-MM-dd HH:mm:ss S yyyy-MM-dd HH:mm:ss GMT t HH:mm T HH:mm:ss u yyyy-MM-dd HH:mm:ss U dddd, MMMM dd, yyyy HH:mm:ss y, Y MMMM, yyyy Here’s an example that uses these custom format specifiers on a DateTime value:\nusing System;class TestDateTimeFormats {static void Main( ) {DateTime dt = new DateTime(2000, 10, 11, 15, 32, 14);// Prints \"2000-10-11T15:32:14\"Console.WriteLine(dt.ToString( ));// Prints \"Wednesday, October 11, 2000\"Console.WriteLine(\"{0}\", dt);// Prints \"10/11/2000\"Console.WriteLine(\"{0:d}\", dt);// Prints \"Wednesday, October 11, 2000\"Console.WriteLine(\"{0:D}\", dt);// Prints \"Wednesday, October 11, 2000 3:32 PM\"Console.WriteLine(\"{0:f}\", dt);// Prints \"Wednesday, October 11, 2000 3:32:14 PM\"Console.WriteLine(\"{0:F}\", dt);// Prints \"10/11/2000 3:32 PM\"Console.WriteLine(\"{0:g}\", dt);// Prints \"10/11/2000 3:32:14 PM\"Console.WriteLine(\"{0:G}\", dt);// Prints \"October 11\"Console.WriteLine(\"{0:m}\", dt);// Prints \"October 11\"Console.WriteLine(\"{0:M}\", dt);// Prints \"Wed, 11 Oct 2000 22:32:14 GMT\"Console.WriteLine(\"{0:r}\", dt);// Prints \"Wed, 11 Oct 2000 22:32:14 GMT\"Console.WriteLine(\"{0:R}\", dt);// Prints \"3:32 PM\"Console.WriteLine(\"{0:t}\", dt);// Prints \"3:32:14 PM\"Console.WriteLine(\"{0:T}\", dt);// Prints \"2000-10-11 22:32:14Z\"Console.WriteLine(\"{0:u}\", dt);// Prints \"Wednesday, October 11, 2000 10:32:14 PM\"Console.WriteLine(\"{0:U}\", dt);// Prints \"October, 2000\"Console.WriteLine(\"{0:y}\", dt);// Prints \"October, 2000\"Console.WriteLine(\"{0:Y}\", dt);// Prints \"Wednesday the 11 day of October in the year 2000\"Console.WriteLine(\"{0:dddd 'the' d 'day of' MMMM 'in the year' yyyy}\", dt);}} Windows and .NET incompatability There are some things to consider when using these default formatters in an international environment.\nConsole.WriteLine(\"{0:t}\", dt); // Prints \"3:32:14 PM\"Console.WriteLine(\"{0:T}\", dt); // Prints \"2000-10-11 22:32:14Z\" The difference between {0:t} and {0:T} has to be taken into account. This difference is due to the fact that .NET has two date time representations—Long ( T ) and Short ( t )—while Windows uses only the Long notation.\nSo, if a user changes the Regional Settings in Windows only the Long notation will follow this change in .NET. This means that the programmer has to perform his own formatting—and not use the default formatters—if he wants to follow the users settings—not something a programmer should expect.\nIt’s worth check out SteveX Blog on String Formats\n","date":"20 September 2008","externalUrl":null,"permalink":"/datetime-format/","section":"Articles","summary":"\nI’m always searching the internet for DateTime formats, so I’ve placed them in my Blog so I’ll also know where I can find them\nDateTime Format Specifiers\nBelow lists the valid format specifiers supported by the Format method on theDateTime type (see System.IFormattable).\n","title":"DateTime Format","type":"articles"},{"content":"\n","date":"20 September 2008","externalUrl":null,"permalink":"/software-requirements/","section":"Articles","summary":"\n","title":"Software Requirements","type":"articles"},{"content":"Just loved this cartoon, they always say a picture says a thousand words ","date":"20 September 2008","externalUrl":null,"permalink":"/the-swing/","section":"Articles","summary":"Just loved this cartoon, they always say a picture says a thousand words ","title":"The Swing","type":"articles"},{"content":"I was having a problem embedding a slide show from Picasa into my BlogEngine.net editor. Basically, the editor kept stripping the embed html. The trick is to edit \\admin\\tinyMCE.ascx file. You need to modify the extended_valid_elements entry. Apparently this is used to define valid html tags for the tinyMCE editor. Here are my additions in red: extended_valid_elements : \"hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style], script[charset|defer|language|src|type],code,iframe[src|width|height|frameborder|name|style],\nembed[type|src|width|height|flashvars|pluginspage]\", Have fun! ","date":"15 September 2008","externalUrl":null,"permalink":"/embed-picasa-slideshows-into-blogengine-net/","section":"Articles","summary":"I was having a problem embedding a slide show from Picasa into my BlogEngine.net editor. Basically, the editor kept stripping the embed html. The trick is to edit \\admin\\tinyMCE.ascx file. You need to modify the extended_valid_elements entry. Apparently this is used to define valid html tags for the tinyMCE editor. Here are my additions in red: ","title":"Embed Picasa slideshows into BlogEngine.net","type":"articles"},{"content":" What version of Visual Studio is the most current? Depending on what you are using and which application you are modifing the following are the latest releases of Visual Studio: Visual Studio 6 (Used for the Legacy VB/C++ apps). Latest build is 9782 and this corresponds to Visual Studio 6.0 SP6. Visual Studio 2003 Version 7.1.6030. This corresponds to VS2003 SP1 and is a MANDATORY install. If you don't have it install it now. Visual Studio 2005 Version 8.0.50727,762 (SP). This corresponds to VS2005 SP1 and is a MANDATORY install. If you don't have it install it now. It can also take over an hour to install. Visual Studio 2008 Version 9.0.21022.8 RTM. This corresponds to the RTM release so if you have VS2008 you have this build. ","date":"8 September 2008","externalUrl":null,"permalink":"/visual-studio-which-version/","section":"Articles","summary":" What version of Visual Studio is the most current? Depending on what you are using and which application you are modifing the following are the latest releases of Visual Studio: Visual Studio 6 (Used for the Legacy VB/C++ apps). Latest build is 9782 and this corresponds to Visual Studio 6.0 SP6. Visual Studio 2003 Version 7.1.6030. This corresponds to VS2003 SP1 and is a MANDATORY install. If you don't have it install it now. Visual Studio 2005 Version 8.0.50727,762 (SP). This corresponds to VS2005 SP1 and is a MANDATORY install. If you don't have it install it now. It can also take over an hour to install. Visual Studio 2008 Version 9.0.21022.8 RTM. This corresponds to the RTM release so if you have VS2008 you have this build. ","title":"Visual Studio, which version?","type":"articles"},{"content":" I've come across this fab system monitoring tool, Spotlight for Windows Spotlight on Windows empowers you to quickly identify and eliminate bottlenecks in the Windows environment For a busy IT professional, it is nearly impossible to diagnose, troubleshoot, and resolve every component affecting Windows Operating System (OS) performance using manual methods. Without a clear view of I/O and system activity, you learn of performance issues only after problems erupt. With its unique graphical view of the Windows OS internals, Spotlight on Windows will empower the user to rapidly eliminate and identify bottlenecks in the Windows environment. Displaying the real-time flow of data within your Windows OS, Spotlight enables you to quickly identify and resolve performance problems. Limitations: Spotlight on Windows is unsupported freeware. The license key is provided in the download package and expires one year after installation. To renew, please revisit this website. An activation key will be made available prior to the expiration date of your current key. http://www.quest.com/spotlight-on-windows/\n","date":"30 July 2008","externalUrl":null,"permalink":"/bottlenecks-and-monitoring/","section":"Articles","summary":" I've come across this fab system monitoring tool, Spotlight for Windows Spotlight on Windows empowers you to quickly identify and eliminate bottlenecks in the Windows environment For a busy IT professional, it is nearly impossible to diagnose, troubleshoot, and resolve every component affecting Windows Operating System (OS) performance using manual methods. Without a clear view of I/O and system activity, you learn of performance issues only after problems erupt. ","title":"Bottlenecks and Monitoring","type":"articles"},{"content":"When working with the SqlCommand you will no doubt have to supply parameters to your command whether it be a Stored Procedure or Text command. Although not as efficient as an actual Stored Procedure there are some powerful things you can achieve using the System.Data.ParameterDirection, or rather other than just Input. The enumeration holds the following values: Input InputOutput Output ReturnValue In this article I will give a working example of each, simple but you will see the idea. At the end I will make a custom object which I will populate using some of these directions. For this example I am working with the AdventureWorks Database for Sql Server 2005. Input The most common direction. using (System.Data.SqlClient.SqlConnection sc1 = new System.Data.SqlClient.SqlConnection(@\"Data Source=REA_ANDREW-PC\\SQLEXPRESS;Initial Catalog=AdventureWorks;\"+\n\"Integrated Security=True\"))\n{\nsc1.Open();\nusing (System.Data.SqlClient.SqlCommand command1 = new System.Data.SqlClient.SqlCommand())\n{\ncommand1.CommandType = CommandType.Text;\ncommand1.Connection = sc1;\n// DIRECTION :: Input\ncommand1.CommandText = \"INSERT INTO [Purchasing].[ShipMethod] (Name,ShipBase,ShipRate)\"+\n\"VALUES (@Name,@ShipBase,@ShipRate)\";\n//Method 1\ncommand1.Parameters.AddWithValue(\"@Name\", \"MyShippingMethod\");\n//Method 2\nSystem.Data.SqlClient.SqlParameter parameter2 = new System.Data.SqlClient.SqlParameter(\"@ShipBase\", 10.00M);\nparameter2.Direction = ParameterDirection.Input;\ncommand1.Parameters.Add(parameter2);\n//Method 3 //Deprecated for AddWithValue\ncommand1.Parameters.Add(\"@ShipRate\", 10.00M); command1.ExecuteNonQuery();\n}\n} Here I have displayed three different syntactical ways of adding parameters to your SqlCommand. The third and final way is deprectaed and you will see this if you try inside Visual Studio. Because of this it will not appear inside intellisense. Output The output is going to look like the above example only I will not give it an intial value and simply assign the value inside the command text. using (System.Data.SqlClient.SqlConnection sc1 = new System.Data.SqlClient.SqlConnection(@\"Data Source=REA_ANDREW-PC\\SQLEXPRESS;Initial Catalog=AdventureWorks;\"+\n\"Integrated Security=True\"))\n{\nsc1.Open();\nusing (System.Data.SqlClient.SqlCommand command1 = new System.Data.SqlClient.SqlCommand())\n{\ncommand1.CommandType = CommandType.Text;\ncommand1.Connection = sc1;\n// DIRECTION :: Input\ncommand1.CommandText = \"select @MyParameter = Count(*) FROM [Purchasing].[ShipMethod]\";\nSystem.Data.SqlClient.SqlParameter paramter1 = command1.Parameters.Add(\"@MyParameter\", SqlDbType.SmallInt);\nparamter1.Direction = ParameterDirection.Output;\ncommand1.ExecuteNonQuery();\n//The following value is now 6, the number of records inside the table\nint newValue = (int)paramter1.Value;\n}\n} Return Value The return value is something which you will return at the end of the statement/s. For this example I need to create a short stored procedure, again i will simply return the count of records from the table: ALTER PROCEDURE CountRows ASDeclare @CountR intSELECT @CountR = Count(*) FROM [Purchasing].[ShipMethod] RETURN @CountR And so the function which will now work with this, and using the ReturnValue direction is as follows: using (System.Data.SqlClient.SqlConnection sc1 = new System.Data.SqlClient.SqlConnection(@\"Data Source=REA_ANDREW-PC\\SQLEXPRESS;Initial Catalog=AdventureWorks;\"+\n\"Integrated Security=True\"))\n{\nsc1.Open();\nusing (System.Data.SqlClient.SqlCommand command1 = new System.Data.SqlClient.SqlCommand())\n{\ncommand1.CommandType = CommandType.StoredProcedure;\ncommand1.Connection = sc1;\n// DIRECTION :: Input\ncommand1.CommandText = \"CountRows\";\nSystem.Data.SqlClient.SqlParameter paramter1 = command1.Parameters.Add(\"@CountR\", SqlDbType.SmallInt);\nparamter1.Direction = ParameterDirection.ReturnValue;\ncommand1.ExecuteNonQuery();\n//The following value is now 6, the number of records inside the table\nint newValue = (int)paramter1.Value;\n}\n} The simple example object I now want to use these counting methods to construct a sample object which will contain simply. Total Record Count List\u0026lt;string\u0026gt; of Shipping Names which can be bound to This is just for an example, I realise lol that I could simply use the List\u0026lt;string\u0026gt; Count property BUT think of it like this. What if you wanted to create a paged object so the list actual only contains say ten items because of a page size you set BUT you still have knowledge of the total number of records through the Total Record Count property, from which you could calculate the total number of pages.!! 🙂 The object namespace WindowsForm_Examples_NET_2\n{ class SimpleObjectOne\n{\nprivate int _recordCount;\nprivate List\u0026lt;string\u0026gt; _shippingNames; public List\u0026lt;string\u0026gt; ShippingNames\n{\nget { return _shippingNames; }\nset { _shippingNames = value; }\n} public int RecordCount\n{\nget { return _recordCount; }\nset { _recordCount = value; }\n}\npublic SimpleObjectOne()\n{\n_shippingNames = new List\u0026lt;string\u0026gt;();\n}\n[System.ComponentModel.DataObjectMethod(\nSystem.ComponentModel.DataObjectMethodType.Select)]\npublic static SimpleObjectOne GetSimpleObjectOne()\n{\nSimpleObjectOne objectOne = new SimpleObjectOne();\nobjectOne.Execute();\nreturn objectOne;\n} private void Execute()\n{\nusing (System.Data.SqlClient.SqlConnection sc1 =\nnew System.Data.SqlClient.SqlConnection(@\"Data Source=REA_ANDREW-PC\\SQLEXPRESS;Initial Catalog=AdventureWorks;\" +\n\"Integrated Security=True\"))\n{\nsc1.Open();\nusing (System.Data.SqlClient.SqlCommand command1 = new System.Data.SqlClient.SqlCommand())\n{\ncommand1.CommandType = System.Data.CommandType.Text;\ncommand1.Connection = sc1;\n// DIRECTION :: Input\ncommand1.CommandText = \"SET @CountRows = (SELECT Count(*) as COUNTR FROM [Purchasing].[ShipMethod]);\" +\n\"SELECT Name FROM [Purchasing].[ShipMethod];\";\nSystem.Data.SqlClient.SqlParameter parameter1 =\ncommand1.Parameters.Add(\"@CountRows\", System.Data.SqlDbType.Int);\nparameter1.Direction = System.Data.ParameterDirection.Output;\nusing (System.Data.SqlClient.SqlDataReader reader = command1.ExecuteReader())\n{\nwhile (reader.Read())\n{\n_shippingNames.Add(reader[\"Name\"] as string);\n}\n}\nRecordCount = (int)parameter1.Value;\n//The following value is now 6, the number of records inside the table\n}\n}\n}\n}\n} An important note to make here, is if you are using the ExecuteReader on a statement and pass in Output parameters, you must close the data reader before you can access these output parameter values. In the above you will see that I encase the data reader in a using statement block. And finally to consume this example I use the following three lines: SimpleObjectOne newObject = SimpleObjectOne.GetSimpleObjectOne();\nint RecordCount = newObject.RecordCount;\nList\u0026lt;string\u0026gt; names = newObject.ShippingNames; I now have 6 as the record count and a list of shipping names. ","date":"30 July 2008","externalUrl":null,"permalink":"/examples-of-using-system-data-parameterdirection-with-sql-server/","section":"Articles","summary":"When working with the SqlCommand you will no doubt have to supply parameters to your command whether it be a Stored Procedure or Text command. Although not as efficient as an actual Stored Procedure there are some powerful things you can achieve using the System.Data.ParameterDirection, or rather other than just Input. ","title":"Examples of using System.Data.ParameterDirection with Sql Server","type":"articles"},{"content":"Working with non-nullable types in C# can be a bit of a pain. For instance when I have a date as a string and need to parse it into a DateTime what should the value be if the parse fails? I can’t use null because DateTime is not a nullable type.\nThis is exactly the dilema I encountered today. No worries, I’ll use DateTime.MinValue that way it is constant and I don’t have to worry about being consistent if I had chosen an arbitrary value of my own.\nWell as it turns out I did have some worries. Sql Server 2000’s minimum DateTime value is not the same, in fact it is quite different. This kept causing errors.\nFor your reference here are some values you should take note of.\nDateTime myDate = DateTime.MinValue; //=\u0026gt; 1/1/0001\nSqlDateTime mySqlDate = SqlDateTime.MinValue; //=\u0026gt; 1/1/1753\n//also note that SQL Server’s smalldatetime min value is 1/1/1900\nIf you need to use the smalldatetime you will need to create your own property to do this\nSo my problem was easily averted, after a quick Google search. I just had to use SqlDateTime.MinValue instead of DateTime.MinValue.\n","date":"25 July 2008","externalUrl":null,"permalink":"/c-datetime-minvalue-is-not-the-same-as-sqldatetime-minvalue/","section":"Articles","summary":"Working with non-nullable types in C# can be a bit of a pain. For instance when I have a date as a string and need to parse it into a DateTime what should the value be if the parse fails? I can’t use null because DateTime is not a nullable type.\n","title":"C# DateTime.MinValue is not the same as SqlDateTime.MinValue","type":"articles"},{"content":"SUMMARY This step-by-step article explains two ways that you can debug SQL Server stored procedures and the necessary configuration settings and steps for each approach. A Visual Studio .NET developer can use the Server Explorer to debug SQL Server stored procedures independently of any Visual Studio project, or the developer can step into the code of the stored procedure directly from managed code in a Visual Basic, Visual C#, or Visual J# project. Debug a stored procedure in standalone mode 1. Open Server Explorer. NOTE: It is not necessary to add a Data Connection to work with a SQL Server server because SQL Server servers are listed under the Servers node also. You will use the Servers node in the steps that follow; however, you can use a Data Connection to you SQL Server server in the same way. 2. Under the Servers node in Server Explorer, expand the SQL Server machine name, expand the SQL Servers node, expand the SQL Server instance, expand the Northwind database node, and then expand the stored procedures node. 3. Right-click the CustOrderHist stored procedure and then click Step Into Stored Procedure. 4. The Run stored procedure dialog box opens, which lists the parameters of the stored procedure. Type ALFKI as the value for the @CustomerID input parameter and then click OK. 5. In the Visual Studio design environment, a window opens that displays the text of the stored procedure. The first executable line of the stored procedure is highlighted. Press F11 to step through the stored procedure to completion. 6. In the Output window, the following message is displayed, which indicates successful execution:\nThe program 'SQL Debugger: T-SQL' has exited with code 0 (0x0). ","date":"24 July 2008","externalUrl":null,"permalink":"/how-to-debug-stored-procedures-in-visual-studio-net/","section":"Articles","summary":"SUMMARY This step-by-step article explains two ways that you can debug SQL Server stored procedures and the necessary configuration settings and steps for each approach. A Visual Studio .NET developer can use the Server Explorer to debug SQL Server stored procedures independently of any Visual Studio project, or the developer can step into the code of the stored procedure directly from managed code in a Visual Basic, Visual C#, or Visual J# project. ","title":"How to debug stored procedures in Visual Studio .NET","type":"articles"},{"content":" Carbonite Well I've been using Carbonite for over 2 years now and with almost 100Gbs backed up online it can't be bad. Carbonite runs in the background all the time, so it is always backing up your data files. It's a don't worry type of backup, just install it and leave it. If I find I need more processing speed or I here the hard drive working hard, then I can pause Carbonite for 24 hours, and it stops it's searching for changed files. It's so simple and restoring files are as easy as coping your files from one drive to another, as Carbonite creates virtual drive of the backed up files. Carbonite\n","date":"19 July 2008","externalUrl":null,"permalink":"/best-windows-backup-tool/","section":"Articles","summary":" Carbonite Well I've been using Carbonite for over 2 years now and with almost 100Gbs backed up online it can't be bad. Carbonite runs in the background all the time, so it is always backing up your data files. It's a don't worry type of backup, just install it and leave it. ","title":"Best Windows Backup Tool","type":"articles"},{"content":" GhostDoc is a free add-in for Visual Studio that automatically generates XML documentation comments for C#. Either by using existing documentation inherited from base classes or implemented interfaces, or by deducing comments from name and type of e.g. methods, properties or parameters. Great plug in and saves so much time Roland Weigelt's G h o s t D o c\n","date":"16 July 2008","externalUrl":null,"permalink":"/ghostdoc/","section":"Articles","summary":" GhostDoc is a free add-in for Visual Studio that automatically generates XML documentation comments for C#. Either by using existing documentation inherited from base classes or implemented interfaces, or by deducing comments from name and type of e.g. methods, properties or parameters. ","title":"GhostDoc","type":"articles"},{"content":"Everywhere I go from client to client I find that when developers create Stored Procedures that just perform the task in hand, and I so often find that no exception handling, comments or transaction based handling has been put in place. So with all this in mind I set to write a structured Stored Procedure to be used as a template for future Stored Procedures that I create.\n-- ============================================= -- Author: Bryan Avery -- Create date: 15th July 2008 -- Description: Import the Taxonomy in to WPPs -- ============================================= ALTER PROCEDURE [dbo].[sp_WaSPs_TaxonomyImport] @Debug bit = 0, @ErrorMessage varchar(2000) OUTPUT, @return_code Int OUTPUT AS BEGIN \u0026ndash; ======================================================== \u0026ndash; Declare SProc variables \u0026ndash; ========================================================\nDECLARE @Error int DECLARE @RowCount int\n\u0026ndash; ======================================================== \u0026ndash; Initialise SProc variables \u0026ndash; ========================================================\nSET NOCOUNT ON;\n\u0026ndash; ======================================================== \u0026ndash; SProc content \u0026ndash; ========================================================\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nDECLARE @Debug_ProcStartTime datetime , @Debug_ProcEndTime datetime\nSET @Debug_ProcStartTime = Getdate()\nSET NOCOUNT OFF\nPRINT ''\nPRINT \u0026lsquo;\u0026ndash; ======================================================\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = PROCEDURE sp_WaSPs_TaxonomyImport\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = @Debug = \u0026rsquo; + IsNull(Cast(@Debug as varchar),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; ======================================================\u0026rsquo;\nPRINT '\u0026rsquo;\nEND\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nPRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; * BEGIN TRANSACTION\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo;\nEND\n\u0026ndash; ======================================================== \u0026ndash; Uncomment the section below if you want to remove all Taxonomy information from the application \u0026ndash; ========================================================\n\u0026ndash; DELETE tbl_WaSPs_GroupArea; \u0026ndash; DELETE tbl_WaSPs_AreaUserName; \u0026ndash; DELETE tbl_WaSPs_AreaSite; \u0026ndash; DELETE tbl_WaSPs_Areas; # \u0026ndash; DELETE tbl_WaSPs_SiteSite; \u0026ndash; DELETE tbl_WaSPs_Sites;\nBEGIN TRANSACTION\nBEGIN TRY\n\u0026ndash; ======================================================== \u0026ndash; Update the areas \u0026ndash; ========================================================\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nPRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; * Update the Areas\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo;\nEND\nUPDATE tbl_WaSPs_Areas SET AreaName = et2.EntityType, EntityTypeCD = et2.EntityTypeCD, myView = \u0026lsquo;False\u0026rsquo; FROM WaspFactory.dbo.tblEntityType et2, tbl_WaSPs_Areas a1 WHERE et2.EntityTypeCD = a1.EntityTypeCD\n\u0026ndash; ======================================================== \u0026ndash; Insert the areas \u0026ndash; ========================================================\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nPRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; * Insert the Areas\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo;\nEND\nINSERT INTO tbl_WaSPs_Areas(AreaName, EntityTypeCD, myView) SELECT et2.EntityType, et2.EntityTypeCD, \u0026lsquo;False\u0026rsquo; FROM WaspFactory.dbo.tblEntityType et2 WHERE et2.EntityTypeCD NOT IN (SELECT EntityTypeCD FROM tbl_WaSPs_Areas)\n\u0026ndash; ======================================================== \u0026ndash; Update the sites \u0026ndash; ========================================================\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nPRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; * Update the Sites\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo;\nEND\nUPDATE tbl_WaSPs_Sites SET title = e1.EntityName, siteid = e1.EntityIdent, entityid = e1.EntityID FROM WaspFactory.dbo.tblEntity e1, tbl_WaSPs_Sites s1 WHERE e1.EntityName IS NOT Null AND e1.EntityId = s1.entityid\n\u0026ndash; ======================================================== \u0026ndash; Insert the sites \u0026ndash; ========================================================\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nPRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; * Insert the Sites\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo;\nEND\nINSERT INTO tbl_WaSPs_Sites(title, siteid, entityid) SELECT EntityName, EntityIdent, EntityID FROM WaspFactory.dbo.tblEntity WHERE EntityName IS NOT Null AND EntityId NOT IN(SELECT entityid FROM tbl_WaSPs_Sites)\n\u0026ndash; ======================================================== \u0026ndash; Remove all the links first \u0026ndash; ========================================================\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nPRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; * Remove all the links first\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo;\nEND\nDELETE tbl_wasps_AreaSite FROM tbl_WaSPs_Areas Areas, WaspFactory.dbo.tblEntityType EntityType, tbl_WaSPs_Sites Sites, WaspFactory.dbo.tblEntity Entity WHERE Areas.EntityTypeCD = EntityType.EntityTypeCD AND Sites.EntityId = Entity.EntityId AND Entity.EntityTypeCD = EntityType.EntityTypeCD\n\u0026ndash; ======================================================== \u0026ndash; Link the sites to the areas \u0026ndash; ========================================================\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nPRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; * Link the sites to the areas\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo;\nEND\nINSERT INTO tbl_wasps_AreaSite(AreaId, SiteId) SELECT AreaId, Id FROM tbl_WaSPs_Areas Areas, WaspFactory.dbo.tblEntityType EntityType, tbl_WaSPs_Sites Sites, WaspFactory.dbo.tblEntity Entity WHERE Areas.EntityTypeCD = EntityType.EntityTypeCD AND Sites.EntityId = Entity.EntityId AND Entity.EntityTypeCD = EntityType.EntityTypeCD AND (AreaId NOT IN (SELECT AreaId FROM tbl_wasps_AreaSite) AND Id NOT IN (SELECT SiteId FROM tbl_wasps_AreaSite))\n\u0026ndash; ======================================================== \u0026ndash; Remove all the site to site links \u0026ndash; ========================================================\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nPRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; * Remove all the site to site links\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo;\nEND\nDELETE tbl_WaSPs_SiteSite WHERE SiteId = fkSiteId\n\u0026ndash; ======================================================== \u0026ndash; Link the site to themself \u0026ndash; ========================================================\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nPRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; * Link the site to themself\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo;\nEND\nINSERT INTO tbl_WaSPs_SiteSite(SiteID, fkSiteId, WaterDirection) SELECT ID, ID, \u0026lsquo;Neither\u0026rsquo; FROM tbl_WaSPs_Sites\n\u0026ndash; ======================================================== \u0026ndash; Delete all the site to site links \u0026ndash; ========================================================\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nPRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; * Delete all the site to site links\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo;\nEND\nDELETE tbl_WaSPs_SiteSite FROM tbl_WaSPs_Sites s1, WaspFactory.dbo.tblEntity e1, WaspFactory.dbo.tblEntityLink el1, WaspFactory.dbo.tblEntity e2, tbl_WaSPs_Sites s2 WHERE e1.EntityId = s1.EntityId AND s1.EntityId = el1.EntityID1 AND el1.EntityID2 = e2.EntityId AND e2.Entityid = s2.EntityId\n\u0026ndash; ======================================================== \u0026ndash; Link the site to other sites \u0026ndash; ========================================================\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nPRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; * Link the site to other sites\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo;\nEND\nINSERT INTO tbl_WaSPs_SiteSite(SiteID, fkSiteId, WaterDirection) SELECT s1.ID, s2.ID, \u0026lsquo;Neither\u0026rsquo; FROM tbl_WaSPs_Sites s1, WaspFactory.dbo.tblEntity e1, WaspFactory.dbo.tblEntityLink el1, WaspFactory.dbo.tblEntity e2, tbl_WaSPs_Sites s2 WHERE e1.EntityId = s1.EntityId AND s1.EntityId = el1.EntityID1 AND el1.EntityID2 = e2.EntityId AND e2.Entityid = s2.EntityId\nEND TRY\nBEGIN CATCH\nSELECT @Error = @@ERROR, @RowCount = @@ROWCOUNT ; IF (@Error \u0026lt;\u0026gt; 0 OR @RowCount = 0) GOTO QuitWithRollback \u0026ndash; (check for error)\nEND CATCH\n\u0026ndash; Commit Transaction\nIF (@@TRANCOUNT \u0026gt; 0)\nBEGIN\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nPRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; * COMMIT TRANSACTION\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo;\nEND\nCOMMIT TRANSACTION\nEND\nGOTO QuitWithSuccess\n\u0026ndash; Error Handling\nQuitWithConcurrencyRollback:\nIF (@@TRANCOUNT \u0026gt; 0)\nBEGIN\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nPRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; * ROLLBACK TRANSACTION\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo;\nEND\nROLLBACK TRANSACTION\nEND\nGOTO QuitWithConcurrencyError\nQuitWithRollback:\nIF (@@TRANCOUNT \u0026gt; 0)\nBEGIN\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nPRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; * ROLLBACK TRANSACTION\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ******************************\u0026rsquo;\nEND\nROLLBACK TRANSACTION\nEND\nGOTO QuitWithError\nQuitWithConcurrencyError:\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nSET @Debug_ProcEndTime = Getdate()\nPRINT \u0026rsquo;\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ======================================================\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = sp_WaSPs_TaxonomyImport\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = RETURN VALUE\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = QuitWithConcurrencyError\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = @ErrorMessage = \u0026rsquo; + IsNull(Cast(@ErrorMessage as varchar),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; = EXECUTION TIME\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = Start = \u0026rsquo; + IsNull(Convert(varchar(24), @Debug_ProcStartTime , 113),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; = End = \u0026rsquo; + IsNull(Convert(varchar(24), @Debug_ProcEndTime , 113),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; = Ellapsed Time (ms) = \u0026rsquo; + IsNull(Cast(Datediff(millisecond, @Debug_ProcStartTime, @Debug_ProcEndTime) as varchar),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; ======================================================\u0026rsquo; PRINT '\u0026rsquo;\nEND\nSET @ErrorMessage = \u0026lsquo;Concurrency Error\u0026rsquo;\nSET @return_code = 3\nRETURN(3)\nQuitWithError:\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nSET @Debug_ProcEndTime = Getdate()\nPRINT \u0026rsquo;\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ======================================================\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = sp_WaSPs_TaxonomyImport\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = RETURN VALUE\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = QuitWithError\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = @Error = \u0026rsquo; + IsNull(Cast(@Error as varchar),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; = @return_code = \u0026rsquo; + IsNull(Cast(@return_code as varchar),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; = EXECUTION TIME\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = Start = \u0026rsquo; + IsNull(Convert(varchar(24), @Debug_ProcStartTime , 113),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; = End = \u0026rsquo; + IsNull(Convert(varchar(24), @Debug_ProcEndTime , 113),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; = Ellapsed Time (ms) = \u0026rsquo; + IsNull(Cast(Datediff(millisecond, @Debug_ProcStartTime, @Debug_ProcEndTime) as varchar),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; ======================================================\u0026rsquo; PRINT '\u0026rsquo;\nEND\nSET @ErrorMessage = \u0026lsquo;SQL Error\u0026rsquo;\nSET @return_code = 2\nRETURN(2)\nQuitWithParameterError:\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nSET @Debug_ProcEndTime = Getdate() PRINT \u0026rsquo;\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ======================================================\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = sp_WaSPs_TaxonomyImport\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = RETURN VALUE\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = QuitWithParameterError\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = @ErrorMessage = \u0026rsquo; + IsNull(Cast(@ErrorMessage as varchar),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; = EXECUTION TIME\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = Start = \u0026rsquo; + IsNull(Convert(varchar(24), @Debug_ProcStartTime , 113),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; = End = \u0026rsquo; + IsNull(Convert(varchar(24), @Debug_ProcEndTime , 113),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; = Ellapsed Time (ms) = \u0026rsquo; + IsNull(Cast(Datediff(millisecond, @Debug_ProcStartTime, @Debug_ProcEndTime) as varchar),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; ======================================================\u0026rsquo; PRINT '\u0026rsquo;\nEND\nSET @return_code = 1\nRETURN(1) # QuitWithSuccess:\nIF ( IsNull(@Debug,0) = 1 ) \u0026ndash; (debug info)\nBEGIN\nSET @Debug_ProcEndTime = Getdate()\nPRINT \u0026rsquo;\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; ======================================================\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = sp_WaSPs_TaxonomyImport\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = RETURN VALUE\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = QuitWithSuccess\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = EXECUTION TIME\u0026rsquo; PRINT \u0026lsquo;\u0026ndash; = Start = \u0026rsquo; + IsNull(Convert(varchar(24), @Debug_ProcStartTime , 113),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; = End = \u0026rsquo; + IsNull(Convert(varchar(24), @Debug_ProcEndTime , 113),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; = Ellapsed Time (ms) = \u0026rsquo; + IsNull(Cast(Datediff(millisecond, @Debug_ProcStartTime, @Debug_ProcEndTime) as varchar),\u0026rsquo;\u0026lt;NULL\u0026gt;\u0026rsquo;) PRINT \u0026lsquo;\u0026ndash; ======================================================\u0026rsquo; PRINT '\u0026rsquo;\nEND\nSET @return_code = 0\nRETURN(0)\nEND\nStoredProcedure\n","date":"16 July 2008","externalUrl":null,"permalink":"/structure-to-stored-procedure/","section":"Articles","summary":"Everywhere I go from client to client I find that when developers create Stored Procedures that just perform the task in hand, and I so often find that no exception handling, comments or transaction based handling has been put in place. So with all this in mind I set to write a structured Stored Procedure to be used as a template for future Stored Procedures that I create.\n","title":"Structure to Stored Procedure","type":"articles"},{"content":" I found this article on csharp station, as a very good insight in to the SqlCommand object, enjoy: This lesson describes the SqlCommand object and how you use it to interact with a data base. Here are the objectives of this lesson: Know what a command object is. Learn how to use the ExecuteReader method to query data. Learn how to use the ExecuteNonQuery method to insert and delete data. Learn how to use the ExecuteScalar method to return a single value. Introduction A SqlCommand object allows you to specify what type of interaction you want to perform with a data base. For example, you can do select, insert, modify, and delete commands on rows of data in a data base table. The SqlCommand object can be used to support disconnected data management scenarios, but in this lesson we will only use the SqlCommand object alone. A later lesson on the SqlDataAdapter will explain how to implement an application that uses disconnected data. This lesson will also show you how to retrieve a single value from a data base, such as the number of records in a table. Creating a SqlCommand Object Similar to other C# objects, you instantiate a SqlCommand object via the new instance declaration, as follows: SqlCommand cmd = new SqlCommand(\"select CategoryName from Categories\", conn); The line above is typical for instantiating a SqlCommand object. It takes a string parameter that holds the command you want to execute and a reference to a SqlConnection object. SqlCommand has a few overloads, which you will see in the examples of this tutorial. Querying Data When using a SQL select command, you retrieve a data set for viewing. To accomplish this with a SqlCommand object, you would use the ExecuteReader method, which returns a SqlDataReader object. We'll discuss the SqlDataReader in a future lesson. The example below shows how to use the SqlCommand object to obtain a SqlDataReader object: // 1. Instantiate a new command with a query and connection\nSqlCommand cmd = new SqlCommand(\"select CategoryName from Categories\", conn); // 2. Call Execute reader to get query results\nSqlDataReader rdr = cmd.ExecuteReader(); In the example above, we instantiate a SqlCommand object, passing the command string and connection object to the constructor. Then we obtain a SqlDataReader object by calling the ExecuteReader method of the SqlCommand object, cmd. This code is part of the ReadData method of Listing 1 in the Putting it All Together section later in this lesson. Inserting Data To insert data into a data base, use the ExecuteNonQuery method of the SqlCommand object. The following code shows how to insert data into a data base table: // prepare command string\nstring insertString = @\"\ninsert into Categories\n(CategoryName, Description)\nvalues ('Miscellaneous', 'Whatever doesn''t fit elsewhere')\";\n// 1. Instantiate a new command with a query and connection\nSqlCommand cmd = new SqlCommand(insertString, conn);\n// 2. Call ExecuteNonQuery to send command\ncmd.ExecuteNonQuery(); The SqlCommand instantiation is just a little different from what you've seen before, but it is basically the same. Instead of a literal string as the first parameter of the SqlCommand constructor, we are using a variable, insertString. The insertString variable is declared just above the SqlCommand declaration. Notice the two apostrophes ('') in the insertString text for the word \"doesn''t\". This is how you escape the apostrophe to get the string to populate column properly. Another observation to make about the insert command is that we explicitly specified the columns CategoryName and Description. The Categories table has a primary key field named CategoryID. We left this out of the list because SQL Server will add this field itself. trying to add a value to a primary key field, such as CategoryID, will generate an exception. To execute this command, we simply call the ExecuteNonQuery method on the SqlCommand instance, cmd. This code is part of the Insertdata method of Listing 1 in the Putting it All Together section later in this lesson. Updating Data The ExecuteNonQuery method is also used for updating data. The following code shows how to update data: // prepare command string\nstring updateString = @\"\nupdate Categories\nset CategoryName = 'Other'\nwhere CategoryName = 'Miscellaneous'\";\n// 1. Instantiate a new command with command text only\nSqlCommand cmd = new SqlCommand(updateString);\n// 2. Set the Connection property\ncmd.Connection = conn;\n// 3. Call ExecuteNonQuery to send command\ncmd.ExecuteNonQuery(); Again, we put the SQL command into a string variable, but this time we used a different SqlCommand constructor that takes only the command. In step 2, we assign the SqlConnection object, conn, to the Connection property of the SqlCommand object, cmd. This could have been done with the same constructor used for the insert command, with two parameters. It demonstrates that you can change the connection object assigned to a command at any time. The ExecuteNonQuery method performs the update command. This code is part of the UpdateData method of Listing 1 in the Putting it All Together section later in this lesson. Deleting Data You can also delete data using the ExecuteNonQuery method. The following example shows how to delete a record from a data base with the ExecuteNonQuery method: // prepare command string\nstring deleteString = @\"\ndelete from Categories\nwhere CategoryName = 'Other'\";\n// 1. Instantiate a new command\nSqlCommand cmd = new SqlCommand();\n// 2. Set the CommandText property\ncmd.CommandText = deleteString;\n// 3. Set the Connection property\ncmd.Connection = conn;\n// 4. Call ExecuteNonQuery to send command\ncmd.ExecuteNonQuery(); This example uses the SqlCommand constructor with no parameters. Instead, it explicity sets the CommandText and Connection properties of the SqlCommand object, cmd. We could have also used either of the two previous SqlCommand constructor overloads, used for the insert or update command, with the same result. This demonstrates that you can change both the command text and the connection object at any time. The ExecuteNonQuery method call sends the command to the data base. This code is part of the DeleteData method of Listing 1 in the Putting it All Together section later in this lesson. Getting Single values Sometimes all you need from a data base is a single value, which could be a count, sum, average, or other aggregated value from a data set. Performing an ExecuteReader and calculating the result in your code is not the most efficient way to do this. The best choice is to let the data base perform the work and return just the single value you need. The following example shows how to do this with the ExecuteScalar method: // 1. Instantiate a new command\nSqlCommand cmd = new SqlCommand(\"select count(*) from Categories\", conn);\n// 2. Call ExecuteNonQuery to send command\nint count = (int)cmd.ExecuteScalar(); The query in the SqlCommand constructor obtains the count of all records from the Categories table. This query will only return a single value. The ExecuteScalar method in step 2 returns this value. Since the return type of ExecuteScalar is type object, we use a cast operator to convert the value to int. This code is part of the GetNumberOfRecords method of Listing 1 in the Putting it All Together section later in this lesson. Putting it All Together For simplicity, we showed snippets of code in previous sections to demonstrate the applicable techniques . It is also useful to have an entire code listing to see how this code is used in a working program. Listing 1 shows all of the code used in this example, along with a driver in the Main method to produce formatted output. Listing 1. SqlConnection Demo\nusing System;\nusing System.Data;\nusing System.Data.SqlClient;\n/// \u0026lt;summary\u0026gt;\n/// Demonstrates how to work with SqlCommand objects\n/// \u0026lt;/summary\u0026gt;\nclass SqlCommandDemo\n{\nSqlConnection conn;\npublic SqlCommandDemo()\n{\n// Instantiate the connection\nconn = new SqlConnection(\n\"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI\");\n}\n// call methods that demo SqlCommand capabilities\nstatic void Main()\n{\nSqlCommandDemo scd = new SqlCommandDemo();\nConsole.WriteLine();\nConsole.WriteLine(\"Categories Before Insert\");\nConsole.WriteLine(\"————————\");\n// use ExecuteReader method\nscd.ReadData();\n// use ExecuteNonQuery method for Insert\nscd.Insertdata();\nConsole.WriteLine();\nConsole.WriteLine(\"Categories After Insert\");\nConsole.WriteLine(\"——————————\");\nscd.ReadData();\n// use ExecuteNonQuery method for Update\nscd.UpdateData();\nConsole.WriteLine();\nConsole.WriteLine(\"Categories After Update\");\nConsole.WriteLine(\"——————————\");\nscd.ReadData();\n// use ExecuteNonQuery method for Delete\nscd.DeleteData();\nConsole.WriteLine();\nConsole.WriteLine(\"Categories After Delete\");\nConsole.WriteLine(\"——————————\");\nscd.ReadData();\n// use ExecuteScalar method\nint numberOfRecords = scd.GetNumberOfRecords();\nConsole.WriteLine();\nConsole.WriteLine(\"Number of Records: {0}\", numberOfRecords);\n}\n/// \u0026lt;summary\u0026gt;\n/// use ExecuteReader method\n/// \u0026lt;/summary\u0026gt;\npublic void ReadData()\n{\nSqlDataReader rdr = null;\ntry\n{\n// Open the connection\nconn.Open();\n// 1. Instantiate a new command with a query and connection\nSqlCommand cmd = new SqlCommand(\"select CategoryName from Categories\", conn);\n// 2. Call Execute reader to get query results\nrdr = cmd.ExecuteReader();\n// print the CategoryName of each record\nwhile (rdr.Read())\n{\nConsole.WriteLine(rdr[0]);\n}\n}\nfinally\n{\n// close the reader\nif (rdr != null)\n{\nrdr.Close();\n}\n// Close the connection\nif (conn != null)\n{\nconn.Close();\n}\n} }\n/// \u0026lt;summary\u0026gt;\n/// use ExecuteNonQuery method for Insert\n/// \u0026lt;/summary\u0026gt;\npublic void Insertdata()\n{\ntry\n{\n// Open the connection\nconn.Open();\n// prepare command string\nstring insertString = @\"\ninsert into Categories\n(CategoryName, Description)\nvalues ('Miscellaneous', 'Whatever doesn''t fit elsewhere')\";\n// 1. Instantiate a new command with a query and connection\nSqlCommand cmd = new SqlCommand(insertString, conn);\n// 2. Call ExecuteNonQuery to send command\ncmd.ExecuteNonQuery();\n}\nfinally\n{\n// Close the connection\nif (conn != null)\n{\nconn.Close();\n}\n} }\n/// \u0026lt;summary\u0026gt;\n/// use ExecuteNonQuery method for Update\n/// \u0026lt;/summary\u0026gt;\npublic void UpdateData()\n{\ntry\n{\n// Open the connection\nconn.Open();\n// prepare command string\nstring updateString = @\"\nupdate Categories\nset CategoryName = 'Other'\nwhere CategoryName = 'Miscellaneous'\";\n// 1. Instantiate a new command with command text only\nSqlCommand cmd = new SqlCommand(updateString);\n// 2. Set the Connection property\ncmd.Connection = conn;\n// 3. Call ExecuteNonQuery to send command\ncmd.ExecuteNonQuery();\n}\nfinally\n{\n// Close the connection\nif (conn != null)\n{\nconn.Close();\n}\n} }\n/// \u0026lt;summary\u0026gt;\n/// use ExecuteNonQuery method for Delete\n/// \u0026lt;/summary\u0026gt;\npublic void DeleteData()\n{\ntry\n{\n// Open the connection\nconn.Open();\n// prepare command string\nstring deleteString = @\"\ndelete from Categories\nwhere CategoryName = 'Other'\";\n// 1. Instantiate a new command\nSqlCommand cmd = new SqlCommand();\n// 2. Set the CommandText property\ncmd.CommandText = deleteString;\n// 3. Set the Connection property\ncmd.Connection = conn;\n// 4. Call ExecuteNonQuery to send command\ncmd.ExecuteNonQuery();\n}\nfinally\n{\n// Close the connection\nif (conn != null)\n{\nconn.Close();\n}\n} }\n/// \u0026lt;summary\u0026gt;\n/// use ExecuteScalar method\n/// \u0026lt;/summary\u0026gt;\n/// \u0026lt;returns\u0026gt;number of records\u0026lt;/returns\u0026gt;\npublic int GetNumberOfRecords()\n{\nint count = -1;\ntry\n{\n// Open the connection\nconn.Open();\n// 1. Instantiate a new command\nSqlCommand cmd = new SqlCommand(\"select count(*) from Categories\", conn);\n// 2. Call ExecuteNonQuery to send command\ncount = (int)cmd.ExecuteScalar();\n}\nfinally\n{\n// Close the connection\nif (conn != null)\n{\nconn.Close();\n}\n}\nreturn count;\n}\n} In Listing 1, the SqlConnection object is instantiated in the SqlCommandDemo structure. This is okay because the object itself will be cleaned up when the CLR garbage collector executes. What is important is that we close the connection when we are done using it. This program opens the connection in a try block and closes it in a finally block in each method. The ReadData method displays the contents of the CategoryName column of the Categories table. We use it several times in the Main method to show the current status of the Categories table, which changes after each of the insert, update, and delete commands. Because of this, it is convenient to reuse to show you the effects after each method call. Summary A SqlCommand object allows you to query and send commands to a data base. It has methods that are specialized for different commands. The ExecuteReader method returns a SqlDataReader object for viewing the results of a select query. For insert, update, and delete SQL commands, you use the ExecuteNonQuery method. If you only need a single aggregate value from a query, the ExecuteScalar is the best choice. ","date":"9 July 2008","externalUrl":null,"permalink":"/the-sqlcommand-object/","section":"Articles","summary":" I found this article on csharp station, as a very good insight in to the SqlCommand object, enjoy: This lesson describes the SqlCommand object and how you use it to interact with a data base. Here are the objectives of this lesson: ","title":"The SqlCommand Object","type":"articles"},{"content":" How many times have you written the perfect application, you spend hours getting it right, only to be told it is running slow. You have performed all the Performance Tuning, and you still get the users saying it is running slowly. One issue is with the clients connection speed, they may be over GPRS or a dial up connection. You have no control over the users connections speeds, so to help this out why not check their connection speed and if it is running slow then provide a warning message. The following code will work out your clients connection speed. The only issue with such code is you have to wait until it is completed before you know the speed. To over come this I use an iFrame on the web page, so to speed of connection is worked out in a separate window to the main application. Meaning the client can continue to work while the calculation is taking place. What and how you tell the client, is really up to you, one way is to display a JavaScript alert message giving them a warning, but be careful not to display this information too many times as they may get a little annoyed being told they have a slow connection speed when they already know they have, int numKB = 512; DateTime start; DateTime end; TimeSpan duration; int length = 0; string checklen = \"\\n\"; private double CalculateSpeed() { Response.Flush(); start = DateTime.Now; length = checklen.Length; for (int i = 0; i \u0026lt; numKB; i++) { hfSpeedTest.Value += \"\".PadRight(1024 – length, \"/*\\\\*\"[0]) + \"\\n\"; Response.Flush(); } end = DateTime.Now; duration = (end – start); double timediff = numKB / duration.TotalSeconds; double speed = System.Math.Round(timediff, 3);hfSpeedTest.Value = \"\"; return speed; } ","date":"8 July 2008","externalUrl":null,"permalink":"/determine-the-connection-speed-of-your-client/","section":"Articles","summary":" How many times have you written the perfect application, you spend hours getting it right, only to be told it is running slow. You have performed all the Performance Tuning, and you still get the users saying it is running slowly. ","title":"Determine the Connection Speed of your client","type":"articles"},{"content":" Writing a Web application with ASP.NET is unbelievably easy. So easy, many developers don’t take the time to structure their applications for great performance. In this article, I’m going to present 10 tips for writing high-performance Web apps. I’m not limiting my comments to ASP.NET applications because they are just one subset of Web applications. This article won’t be the definitive guide for performance-tuning Web applications—an entire book could easily be devoted to that. Instead, think of this as a good place to start. Before becoming a workaholic, I used to do a lot of rock climbing. Prior to any big climb, I’d review the route in the guidebook and read the recommendations made by people who had visited the site before. But, no matter how good the guidebook, you need actual rock climbing experience before attempting a particularly challenging climb. Similarly, you can only learn how to write high-performance Web applications when you’re faced with either fixing performance problems or running a high-throughput site. My personal experience comes from having been an infrastructure Program Manager on the ASP.NET team at Microsoft, running and managing www.asp.net, and helping architect Community Server, which is the next version of several well-known ASP.NET applications (ASP.NET Forums, .Text, and nGallery combined into one platform). I’m sure that some of the tips that have helped me will help you as well. You should think about the separation of your application into logical tiers. You might have heard of the term 3-tier (or n-tier) physical architecture. These are usually prescribed architecture patterns that physically divide functionality across processes and/or hardware. As the system needs to scale, more hardware can easily be added. There is, however, a performance hit associated with process and machine hopping, thus it should be avoided. So, whenever possible, run the ASP.NET pages and their associated components together in the same application. Because of the separation of code and the boundaries between tiers, using Web services or remoting will decrease performance by 20 percent or more. The data tier is a bit of a different beast since it is usually better to have dedicated hardware for your database. However, the cost of process hopping to the database is still high, thus performance on the data tier is the first place to look when optimizing your code. Before diving in to fix performance problems in your applications, make sure you profile your applications to see exactly where the problems lie. Key performance counters (such as the one that indicates the percentage of time spent performing garbage collections) are also very useful for finding out where applications are spending the majority of their time. Yet the places where time is spent are often quite unintuitive. There are two types of performance improvements described in this article: large optimizations, such as using the ASP.NET Cache, and tiny optimizations that repeat themselves. These tiny optimizations are sometimes the most interesting. You make a small change to code that gets called thousands and thousands of times. With a big optimization, you might see overall performance take a large jump. With a small one, you might shave a few milliseconds on a given request, but when compounded across the total requests per day, it can result in an enormous improvement. Performance on the Data Tier When it comes to performance-tuning an application, there is a single litmus test you can use to prioritize work: does the code access the database? If so, how often? Note that the same test could be applied for code that uses Web services or remoting, too, but I’m not covering those in this article. If you have a database request required in a particular code path and you see other areas such as string manipulations that you want to optimize first, stop and perform your litmus test. Unless you have an egregious performance problem, your time would be better utilized trying to optimize the time spent in and connected to the database, the amount of data returned, and how often you make round-trips to and from the database. With that general information established, let’s look at ten tips that can help your application perform better. I’ll begin with the changes that can make the biggest difference. Tip 1—Return Multiple Resultsets Review your database code to see if you have request paths that go to the database more than once. Each of those round-trips decreases the number of requests per second your application can serve. By returning multiple resultsets in a single database request, you can cut the total time spent communicating with the database. You’ll be making your system more scalable, too, as you’ll cut down on the work the database server is doing managing requests. While you can return multiple resultsets using dynamic SQL, I prefer to use stored procedures. It’s arguable whether business logic should reside in a stored procedure, but I think that if logic in a stored procedure can constrain the data returned (reduce the size of the dataset, time spent on the network, and not having to filter the data in the logic tier), it’s a good thing. Using a SqlCommand instance and its ExecuteReader method to populate strongly typed business classes, you can move the resultset pointer forward by calling NextResult. Figure 1 shows a sample conversation populating several ArrayLists with typed classes. Returning only the data you need from the database will additionally decrease memory allocations on your server. Figure 1 Extracting Multiple Resultsets from a DataReader // read the first resultset\nreader = command.ExecuteReader(); // read the data from that resultset\nwhile (reader.Read()) {\nsuppliers.Add(PopulateSupplierFromIDataReader( reader ));\n}\n// read the next resultset\nreader.NextResult();\n// read the data from that second resultset\nwhile (reader.Read()) {\nproducts.Add(PopulateProductFromIDataReader( reader ));\n}\nTip 2—Paged Data Access The ASP.NET DataGrid exposes a wonderful capability: data paging support. When paging is enabled in the DataGrid, a fixed number of records is shown at a time. Additionally, paging UI is also shown at the bottom of the DataGrid for navigating through the records. The paging UI allows you to navigate backwards and forwards through displayed data, displaying a fixed number of records at a time. There’s one slight wrinkle. Paging with the DataGrid requires all of the data to be bound to the grid. For example, your data layer will need to return all of the data and then the DataGrid will filter all the displayed records based on the current page. If 100,000 records are returned when you’re paging through the DataGrid, 99,975 records would be discarded on each request (assuming a page size of 25). As the number of records grows, the performance of the application will suffer as more and more data must be sent on each request. One good approach to writing better paging code is to use stored procedures. Figure 2 shows a sample stored procedure that pages through the Orders table in the Northwind database. In a nutshell, all you’re doing here is passing in the page index and the page size. The appropriate resultset is calculated and then returned. Figure 2 Paging Through the Orders Table CREATE PROCEDURE northwind_OrdersPaged\n(\n@PageIndex int, @PageSize int\n)\nAS\nBEGIN\nDECLARE @PageLowerBound int\nDECLARE @PageUpperBound int\nDECLARE @RowsToReturn int — First set the rowcount\nSET @RowsToReturn = @PageSize * (@PageIndex + 1)\nSET ROWCOUNT @RowsToReturn\n— Set the page bounds\nSET @PageLowerBound = @PageSize * @PageIndex\nSET @PageUpperBound = @PageLowerBound + @PageSize + 1\n— Create a temp table to store the select results\nCREATE TABLE #PageIndex (\nIndexId int IDENTITY (1, 1) NOT NULL,\nOrderID int\n)\n— Insert into the temp table\nINSERT INTO #PageIndex (OrderID)\nSELECT OrderID\nFROM Orders\nORDER BY OrderID DESC\n— Return total count\nSELECT COUNT(OrderID) FROM Orders\n— Return paged results\nSELECT O.*\nFROM Orders O,\n#PageIndex PageIndex\nWHERE O.OrderID = PageIndex.OrderID AND\nPageIndex.IndexID \u0026gt; @PageLowerBound AND\nPageIndex.IndexID \u0026lt; @PageUpperBound\nORDER BY PageIndex.IndexID\nEND\nIn Community Server, we wrote a paging server control to do all the data paging. You’ll see that I am using the ideas discussed in Tip 1, returning two resultsets from one stored procedure: the total number of records and the requested data. The total number of records returned can vary depending on the query being executed. For example, a WHERE clause can be used to constrain the data returned. The total number of records to be returned must be known in order to calculate the total pages to be displayed in the paging UI. For example, if there are 1,000,000 total records and a WHERE clause is used that filters this to 1,000 records, the paging logic needs to be aware of the total number of records to properly render the paging UI. Tip 3—Connection Pooling Setting up the TCP connection between your Web application and SQL Server™ can be an expensive operation. Developers at Microsoft have been able to take advantage of connection pooling for some time now, allowing them to reuse connections to the database. Rather than setting up a new TCP connection on each request, a new connection is set up only when one is not available in the connection pool. When the connection is closed, it is returned to the pool where it remains connected to the database, as opposed to completely tearing down that TCP connection. Of course you need to watch out for leaking connections. Always close your connections when you’re finished with them. I repeat: no matter what anyone says about garbage collection within the Microsoft® .NET Framework, always call Close or Dispose explicitly on your connection when you are finished with it. Do not trust the common language runtime (CLR) to clean up and close your connection for you at a predetermined time. The CLR will eventually destroy the class and force the connection closed, but you have no guarantee when the garbage collection on the object will actually happen. To use connection pooling optimally, there are a couple of rules to live by. First, open the connection, do the work, and then close the connection. It’s okay to open and close the connection multiple times on each request if you have to (optimally you apply Tip 1) rather than keeping the connection open and passing it around through different methods. Second, use the same connection string (and the same thread identity if you’re using integrated authentication). If you don’t use the same connection string, for example customizing the connection string based on the logged-in user, you won’t get the same optimization value provided by connection pooling. And if you use integrated authentication while impersonating a large set of users, your pooling will also be much less effective. The .NET CLR data performance counters can be very useful when attempting to track down any performance issues that are related to connection pooling. Whenever your application is connecting to a resource, such as a database, running in another process, you should optimize by focusing on the time spent connecting to the resource, the time spent sending or retrieving data, and the number of round-trips. Optimizing any kind of process hop in your application is the first place to start to achieve better performance. The application tier contains the logic that connects to your data layer and transforms data into meaningful class instances and business processes. For example, in Community Server, this is where you populate a Forums or Threads collection, and apply business rules such as permissions; most importantly it is where the Caching logic is performed. Tip 4—ASP.NET Cache API One of the very first things you should do before writing a line of application code is architect the application tier to maximize and exploit the ASP.NET Cache feature. If your components are running within an ASP.NET application, you simply need to include a reference to System.Web.dll in your application project. When you need access to the Cache, use the HttpRuntime.Cache property (the same object is also accessible through Page.Cache and HttpContext.Cache). There are several rules for caching data. First, if data can be used more than once it’s a good candidate for caching. Second, if data is general rather than specific to a given request or user, it’s a great candidate for the cache. If the data is user- or request-specific, but is long lived, it can still be cached, but may not be used as frequently. Third, an often overlooked rule is that sometimes you can cache too much. Generally on an x86 machine, you want to run a process with no higher than 800MB of private bytes in order to reduce the chance of an out-of-memory error. Therefore, caching should be bounded. In other words, you may be able to reuse a result of a computation, but if that computation takes 10 parameters, you might attempt to cache on 10 permutations, which will likely get you into trouble. One of the most common support calls for ASP.NET is out-of-memory errors caused by overcaching, especially of large datasets.Common Performance Myths One of the most common myths is that C# code is faster than Visual Basic code. There is a grain of truth in this, as it is possible to take several performance-hindering actions in Visual Basic that are not possible to accomplish in C#, such as not explicitly declaring types. But if good programming practices are followed, there is no reason why Visual Basic and C# code cannot execute with nearly identical performance. To put it more succinctly, similar code produces similar results. Another myth is that codebehind is faster than inline, which is absolutely false. It doesn’t matter where your code for your ASP.NET application lives, whether in a codebehind file or inline with the ASP.NET page. Sometimes I prefer to use inline code as changes don’t incur the same update costs as codebehind. For example, with codebehind you have to update the entire codebehind DLL, which can be a scary proposition. Myth number three is that components are faster than pages. This was true in Classic ASP when compiled COM servers were much faster than VBScript. With ASP.NET, however, both pages and components are classes. Whether your code is inline in a page, within a codebehind, or in a separate component makes little performance difference. Organizationally, it is better to group functionality logically this way, but again it makes no difference with regard to performance. The final myth I want to dispel is that every functionality that you want to occur between two apps should be implemented as a Web service. Web services should be used to connect disparate systems or to provide remote access to system functionality or behaviors. They should not be used internally to connect two similar systems. While easy to use, there are much better alternatives. The worst thing you can do is use Web services for communicating between ASP and ASP.NET applications running on the same server, which I’ve witnessed all too frequently. Figure 3 ASP.NET Cache There are a several great features of the Cache that you need to know. The first is that the Cache implements a least-recently-used algorithm, allowing ASP.NET to force a Cache purge—automatically removing unused items from the Cache—if memory is running low. Secondly, the Cache supports expiration dependencies that can force invalidation. These include time, key, and file. Time is often used, but with ASP.NET 2.0 a new and more powerful invalidation type is being introduced: database cache invalidation. This refers to the automatic removal of entries in the cache when data in the database changes. For more information on database cache invalidation, see Dino Esposito’s Cutting Edge column in the July 2004 issue of MSDN®Magazine. For a look at the architecture of the cache, see Figure 3. Tip 5—Per-Request Caching Earlier in the article, I mentioned that small improvements to frequently traversed code paths can lead to big, overall performance gains. One of my absolute favorites of these is something I’ve termed per-request caching. Whereas the Cache API is designed to cache data for a long period or until some condition is met, per-request caching simply means caching the data for the duration of the request. A particular code path is accessed frequently on each request but the data only needs to be fetched, applied, modified, or updated once. This sounds fairly theoretical, so let’s consider a concrete example. In the Forums application of Community Server, each server control used on a page requires personalization data to determine which skin to use, the style sheet to use, as well as other personalization data. Some of this data can be cached for a long period of time, but some data, such as the skin to use for the controls, is fetched once on each request and reused multiple times during the execution of the request. To accomplish per-request caching, use the ASP.NET HttpContext. An instance of HttpContext is created with every request and is accessible anywhere during that request from the HttpContext.Current property. The HttpContext class has a special Items collection property; objects and data added to this Items collection are cached only for the duration of the request. Just as you can use the Cache to store frequently accessed data, you can use HttpContext.Items to store data that you’ll use only on a per-request basis. The logic behind this is simple: data is added to the HttpContext.Items collection when it doesn’t exist, and on subsequent lookups the data found in HttpContext.Items is simply returned. Tip 6—Background Processing The path through your code should be as fast as possible, right? There may be times when you find yourself performing expensive tasks on each request or once every n requests. Sending out e-mails or parsing and validation of incoming data are just a few examples. When tearing apart ASP.NET Forums 1.0 and rebuilding what became Community Server, we found that the code path for adding a new post was pretty slow. Each time a post was added, the application first needed to ensure that there were no duplicate posts, then it had to parse the post using a “badword” filter, parse the post for emoticons, tokenize and index the post, add the post to the moderation queue when required, validate attachments, and finally, once posted, send e-mail notifications out to any subscribers. Clearly, that’s a lot of work. It turns out that most of the time was spent in the indexing logic and sending e-mails. Indexing a post was a time-consuming operation, and it turned out that the built-in System.Web.Mail functionality would connect to an SMTP server and send the e-mails serially. As the number of subscribers to a particular post or topic area increased, it would take longer and longer to perform the AddPost function. Indexing e-mail didn’t need to happen on each request. Ideally, we wanted to batch this work together and index 25 posts at a time or send all the e-mails every five minutes. We decided to use the same code I had used to prototype database cache invalidation for what eventually got baked into Visual Studio® 2005. The Timer class, found in the System.Threading namespace, is a wonderfully useful, but less well-known class in the .NET Framework, at least for Web developers. Once created, the Timer will invoke the specified callback on a thread from the ThreadPool at a configurable interval. This means you can set up code to execute without an incoming request to your ASP.NET application, an ideal situation for background processing. You can do work such as indexing or sending e-mail in this background process too. There are a couple of problems with this technique, though. If your application domain unloads, the timer instance will stop firing its events. In addition, since the CLR has a hard gate on the number of threads per process, you can get into a situation on a heavily loaded server where timers may not have threads to complete on and can be somewhat delayed. ASP.NET tries to minimize the chances of this happening by reserving a certain number of free threads in the process and only using a portion of the total threads for request processing. However, if you have lots of asynchronous work, this can be an issue. There is not enough room to go into the code here, but you can download a digestible sample at www.rob-howard.net. Just grab the slides and demos from the Blackbelt TechEd 2004 presentation. One simple method is to use the ThreadPool, with any background processes you must make sure you capture any exception so as you know something has gone wrong, as shown below: ThreadPool.QueueUserWorkItem(delegate { MyCode.Import(); });\nTip 7—Page Output Caching and Proxy Servers ASP.NET is your presentation layer (or should be); it consists of pages, user controls, server controls (HttpHandlers and HttpModules), and the content that they generate. If you have an ASP.NET page that generates output, whether HTML, XML, images, or any other data, and you run this code on each request and it generates the same output, you have a great candidate for page output caching. By simply adding this line to the top of your page \u0026lt;%@ Page OutputCache VaryByParams=”none” Duration=”60″ %\u0026gt; you can effectively generate the output for this page once and reuse it multiple times for up to 60 seconds, at which point the page will re-execute and the output will once be again added to the ASP.NET Cache. This behavior can also be accomplished using some lower-level programmatic APIs, too. There are several configurable settings for output caching, such as the VaryByParams attribute just described. VaryByParams just happens to be required, but allows you to specify the HTTP GET or HTTP POST parameters to vary the cache entries. For example, default/?Report=1 or default/?Report=2 could be output-cached by simply setting VaryByParam=”Report”. Additional parameters can be named by specifying a semicolon-separated list. Many people don’t realize that when the Output Cache is used, the ASP.NET page also generates a set of HTTP headers that downstream caching servers, such as those used by the Microsoft Internet Security and Acceleration Server or by Akamai. When HTTP Cache headers are set, the documents can be cached on these network resources, and client requests can be satisfied without having to go back to the origin server. Using page output caching, then, does not make your application more efficient, but it can potentially reduce the load on your server as downstream caching technology caches documents. Of course, this can only be anonymous content; once it’s downstream, you won’t see the requests anymore and can’t perform authentication to prevent access to it. Tip 8—Run IIS 6.0 (If Only for Kernel Caching) If you’re not running IIS 6.0 (Windows Server™ 2003), you’re missing out on some great performance enhancements in the Microsoft Web server. In Tip 7, I talked about output caching. In IIS 5.0, a request comes through IIS and then to ASP.NET. When caching is involved, an HttpModule in ASP.NET receives the request, and returns the contents from the Cache. If you’re using IIS 6.0, there is a nice little feature called kernel caching that doesn’t require any code changes to ASP.NET. When a request is output-cached by ASP.NET, the IIS kernel cache receives a copy of the cached data. When a request comes from the network driver, a kernel-level driver (no context switch to user mode) receives the request, and if cached, flushes the cached data to the response, and completes execution. This means that when you use kernel-mode caching with IIS and ASP.NET output caching, you’ll see unbelievable performance results. At one point during the Visual Studio 2005 development of ASP.NET, I was the program manager responsible for ASP.NET performance. The developers did the magic, but I saw all the reports on a daily basis. The kernel mode caching results were always the most interesting. The common characteristic was network saturation by requests/responses and IIS running at about five percent CPU utilization. It was amazing! There are certainly other reasons for using IIS 6.0, but kernel mode caching is an obvious one. Tip 9—Use Gzip Compression While not necessarily a server performance tip (since you might see CPU utilization go up), using gzip compression can decrease the number of bytes sent by your server. This gives the perception of faster pages and also cuts down on bandwidth usage. Depending on the data sent, how well it can be compressed, and whether the client browsers support it (IIS will only send gzip compressed content to clients that support gzip compression, such as Internet Explorer 6.0 and Firefox), your server can serve more requests per second. In fact, just about any time you can decrease the amount of data returned, you will increase requests per second. The good news is that gzip compression is built into IIS 6.0 and is much better than the gzip compression used in IIS 5.0. Unfortunately, when attempting to turn on gzip compression in IIS 6.0, you may not be able to locate the setting on the properties dialog in IIS. The IIS team built awesome gzip capabilities into the server, but neglected to include an administrative UI for enabling it. To enable gzip compression, you have to spelunk into the innards of the XML configuration settings of IIS 6.0 (which isn’t for the faint of heart). By the way, the credit goes to Scott Forsyth of OrcsWeb who helped me figure this out for the www.asp.net severs hosted by OrcsWeb. Rather than include the procedure in this article, just read the article by Brad Wilson at IIS6 Compression. There’s also a Knowledge Base article on enabling compression for ASPX, available at Enable ASPX Compression in IIS. It should be noted, however, that dynamic compression and kernel caching are mutually exclusive on IIS 6.0 due to some implementation details. Tip 10—Server Control View State View state is a fancy name for ASP.NET storing some state data in a hidden input field inside the generated page. When the page is posted back to the server, the server can parse, validate, and apply this view state data back to the page’s tree of controls. View state is a very powerful capability since it allows state to be persisted with the client and it requires no cookies or server memory to save this state. Many ASP.NET server controls use view state to persist settings made during interactions with elements on the page, for example, saving the current page that is being displayed when paging through data. There are a number of drawbacks to the use of view state, however. First of all, it increases the total payload of the page both when served and when requested. There is also an additional overhead incurred when serializing or deserializing view state data that is posted back to the server. Lastly, view state increases the memory allocations on the server. Several server controls, the most well known of which is the DataGrid, tend to make excessive use of view state, even in cases where it is not needed. The default behavior of the ViewState property is enabled, but if you don’t need it, you can turn it off at the control or page level. Within a control, you simply set the EnableViewState property to false, or you can set it globally within the page using this setting: \u0026lt;%@ Page EnableViewState=”false” %\u0026gt; If you are not doing postbacks in a page or are always regenerating the controls on a page on each request, you should disable view state at the page level. Conclusion I’ve offered you some tips that I’ve found useful for writing high-performance ASP.NET applications. As I mentioned at the beginning of this article, this is more a preliminary guide than the last word on ASP.NET performance. (More information on improving the performance of ASP.NET apps can be found at Improving ASP.NET Performance.) Only through your own experience can you find the best way to solve your unique performance problems. However, during your journey, these tips should provide you with good guidance. In software development, there are very few absolutes; every application is unique. It’s also worth taking a look at Mads Kristensen blog: Checklist for high quality websites part 1 Checklist for high quality websites part 2 ","date":"3 July 2008","externalUrl":null,"permalink":"/10-tips-for-writing-high-performance-web-applications/","section":"Articles","summary":" Writing a Web application with ASP.NET is unbelievably easy. So easy, many developers don’t take the time to structure their applications for great performance. In this article, I’m going to present 10 tips for writing high-performance Web apps. I’m not limiting my comments to ASP.NET applications because they are just one subset of Web applications. This article won’t be the definitive guide for performance-tuning Web applications—an entire book could easily be devoted to that. Instead, think of this as a good place to start. Before becoming a workaholic, I used to do a lot of rock climbing. Prior to any big climb, I’d review the route in the guidebook and read the recommendations made by people who had visited the site before. But, no matter how good the guidebook, you need actual rock climbing experience before attempting a particularly challenging climb. Similarly, you can only learn how to write high-performance Web applications when you’re faced with either fixing performance problems or running a high-throughput site. My personal experience comes from having been an infrastructure Program Manager on the ASP.NET team at Microsoft, running and managing www.asp.net, and helping architect Community Server, which is the next version of several well-known ASP.NET applications (ASP.NET Forums, .Text, and nGallery combined into one platform). I’m sure that some of the tips that have helped me will help you as well. You should think about the separation of your application into logical tiers. You might have heard of the term 3-tier (or n-tier) physical architecture. These are usually prescribed architecture patterns that physically divide functionality across processes and/or hardware. As the system needs to scale, more hardware can easily be added. There is, however, a performance hit associated with process and machine hopping, thus it should be avoided. So, whenever possible, run the ASP.NET pages and their associated components together in the same application. Because of the separation of code and the boundaries between tiers, using Web services or remoting will decrease performance by 20 percent or more. The data tier is a bit of a different beast since it is usually better to have dedicated hardware for your database. However, the cost of process hopping to the database is still high, thus performance on the data tier is the first place to look when optimizing your code. Before diving in to fix performance problems in your applications, make sure you profile your applications to see exactly where the problems lie. Key performance counters (such as the one that indicates the percentage of time spent performing garbage collections) are also very useful for finding out where applications are spending the majority of their time. Yet the places where time is spent are often quite unintuitive. There are two types of performance improvements described in this article: large optimizations, such as using the ASP.NET Cache, and tiny optimizations that repeat themselves. These tiny optimizations are sometimes the most interesting. You make a small change to code that gets called thousands and thousands of times. With a big optimization, you might see overall performance take a large jump. With a small one, you might shave a few milliseconds on a given request, but when compounded across the total requests per day, it can result in an enormous improvement. Performance on the Data Tier When it comes to performance-tuning an application, there is a single litmus test you can use to prioritize work: does the code access the database? If so, how often? Note that the same test could be applied for code that uses Web services or remoting, too, but I’m not covering those in this article. If you have a database request required in a particular code path and you see other areas such as string manipulations that you want to optimize first, stop and perform your litmus test. Unless you have an egregious performance problem, your time would be better utilized trying to optimize the time spent in and connected to the database, the amount of data returned, and how often you make round-trips to and from the database. With that general information established, let’s look at ten tips that can help your application perform better. I’ll begin with the changes that can make the biggest difference. Tip 1—Return Multiple Resultsets Review your database code to see if you have request paths that go to the database more than once. Each of those round-trips decreases the number of requests per second your application can serve. By returning multiple resultsets in a single database request, you can cut the total time spent communicating with the database. You’ll be making your system more scalable, too, as you’ll cut down on the work the database server is doing managing requests. While you can return multiple resultsets using dynamic SQL, I prefer to use stored procedures. It’s arguable whether business logic should reside in a stored procedure, but I think that if logic in a stored procedure can constrain the data returned (reduce the size of the dataset, time spent on the network, and not having to filter the data in the logic tier), it’s a good thing. Using a SqlCommand instance and its ExecuteReader method to populate strongly typed business classes, you can move the resultset pointer forward by calling NextResult. Figure 1 shows a sample conversation populating several ArrayLists with typed classes. Returning only the data you need from the database will additionally decrease memory allocations on your server. Figure 1 Extracting Multiple Resultsets from a DataReader // read the first resultset\nreader = command.ExecuteReader(); // read the data from that resultset\nwhile (reader.Read()) {\nsuppliers.Add(PopulateSupplierFromIDataReader( reader ));\n}\n// read the next resultset\nreader.NextResult();\n// read the data from that second resultset\nwhile (reader.Read()) {\nproducts.Add(PopulateProductFromIDataReader( reader ));\n}\n","title":"10 Tips for Writing High-Performance Web Applications","type":"articles"},{"content":" Background ViewState is a feature provided by ASP.Net that stores information for server controls used on a web page. The primary advantage of this feature from a developer perspective is that it keeps the values of controls on a form. If the user forgot a single required field on a form, ASP.Net can put back the other values they had entered rather than forcing the developer to repopulate them. The information is encoded into a string and placed in a hidden form field called “__VIEWSTATE” that is sent to the client with the response (you can see this by using View Source in your browser when you view a / page). ASP.Net by default also calculates a “hash” of the information and adds it to the ViewState, then on a postback it can validate that the data has not been corrupted. That is a basic description of what viewstate is and how it is implemented, this article will focus on where the viewstate information is stored. The Problem After converting our web site from ASP to ASP.Net, we began to have problems with viewstate exceptions. We would receive \"The View State is invalid for this page and might be corrupted\" about 50 times a day. We searched for known causes for this problem and none of them applied to our situation. After several network traces and calls to Microsoft Support, we determined that when network retransmissions occurred the client would sometimes have a corrupt version of the HTML page (we were never able to determine why TCP did not detect the corruption). If the corruption happened to occur inside the viewstate hidden field value, it would cause the exceptions (the recomputed hash on the server did not match the original hash). We also determined that several browsers (such as older WebTV clients) could not handle large hidden form fields. Our solution was to save the viewstate for the pages on the web server using the Session object instead of the HTML result sent to the client. Benefits of Server Side ViewState Avoid corruption problems Avoid issues with browsers that limit the maximum size of hidden fields Reduced client page size – since the viewstate information is stored on the server it is not sent in the response to the client which saves download time and bandwidth Disadvantages of Server Side ViewState\nUses server side memory for the in-process session object Not as obvious to developers how much space is used by viewstate The Solution The idea is to override the default handling of viewstate provided by ASP.Net and implement a custom implementation to store the viewstate information on the server. Originally I was not enthusiastic about the idea of rewriting some of the basic functionality provided by ASP.Net, but it was very easy to do and eliminated our problems. Since the viewstate is specific to each user, we decided to store the information using the Session object. Our servers use in-process session state (stored in web server memory), so we wanted to limit the amount of viewstate we had to store for each user. We cannot simply store the last viewstate for user, however, because a user can visit a page in Internet Explorer, hit the back button to a previous page and push a button (which would require the viewstate for that page). This requires us to support multiple versions of viewstate for each user. The number of page viewstate values to store is a tradeoff between memory and support for pressing the back button a number of times. The example solution stores the last 5 viewstate values for each user. The viewstate values are stored in a circular array using the modulus operator (% in C#). Every time a user requests a new page on the site, the code increments a request number and uses that number as a key to the proper viewstate in the array on the server. The code uses the modulus of the request number and the size of the array to determine the index into the circular array. This starts storing viewstate for the first page (request number 1) in index 1 of the array (1 % 5 = 1), request 2 would use index 2, etc. This continues until the request number hits 5, which wraps back around and uses index position 0. This is a simple way to use a fixed size array efficiently. The code stores the request number in the “__VIEWSTATE” field that was previously used to store the actual viewstate information. The code consults the web.config file to determine if it should use server side or client side viewstate (changes to the web.config will drop the in-process Session object for the user which will drop all current viewstate, make changes to this during off peak times). Instructions for Using The first step in implementing the solution is to download the two C# files, below, that implement the server side functionality and add them to your ASP.Net project. BasePage.cs This file includes the class BasePage which is used as a parent class for all pages on the site and can be used without modification. The use of a custom base class has many advantages for an ASP.Net site, in this case it is used to override the default viewstate handling provided by System.Web.UI.Page. The two methods that this class overrides are LoadPageStateFromPersistenceMedium() which is called to reload the viewstate on a postback, and SavePageStateToPersistenceMedium() which is called to save the viewstate before sending the results to the client. The override of these methods simply check if server side viewstate is enabled, then call methods to do the work if it is (otherwise they just invoke the original Page class methods). The LoadViewState() method checks for the __VIEWSTATE field and attempts to convert it to a long (which would fail if the viewstate was actually the original encoded string). If it successfully retrieves the value, it uses another class viewStateSvrMgr to retrieve the viewstate from the session. The SaveViewState() method uses the viewStateSvrMgr class to save the viewstate to the session, and writes the hidden form field __VIEWSTATE to the client page with the request number key. If you are using the .Net 1.1 framework, you should change the name used for the hidden field value, which is stored in the constant VIEW_STATE_FIELD_NAME in this file (anything other than __VIEWSTATE). All web pages for the site must derive from the BasePage class. The default file webForm1/.cs in an ASP.Net project has the original class declaration “public class WebForm1 : System.Web.UI.Page”, this is changed instead to “public class WebForm1 : ServerSideViewstate.BasePage”. viewStateSvrMgr.cs This provides the majority of the code required for server side viewstate. A constant at the top of the file VIEW_STATE_NUM_PAGES controls the number of viewstate values kept for each user. This can be adjusted as necessary to conserve memory, but if the user hit the back button more times than this array size and did a postback, the viewstate data would not be present which will affect page behavior for controls and events. This file also uses a technique that stores an object in session rather than storing multiple independent session variables. The GetViewStateSvrMgr() method checks if an object of this class has already been created and stored in session or if it needs to do so. Then the class can simply store local variables that are all stored in that single session object, which helps avoid pollution of the Session with lots of independent keys with no relation between them. Pages that need to use the services of the class call GetViewStateSvrMgr() and get an instance of the class they can use to get/save viewstate information. The property ServerSideEnabled abstracts the check for whether the server side viewstate is enabled or not (via the web.config setting). The methods SaveViewState() and GetViewState() manage the circular array which is a member of the class, and hence is stored in the object that is placed in the session object for this user. The last step is to add the following to the web.config file (place just above the \u0026lt;/configuration\u0026gt; entry: \u0026lt;appSettings\u0026gt;\n\u0026lt;add key=\"ServerSideViewState\" value=\"true\" /\u0026gt;\n\u0026lt;/appSettings\u0026gt; Testing Once the files have been added to the project, the pages have been changed to derive from the BasePage class, and the changes to web.config have been made the site will start to use the session to store viewstate. This can be validated by visiting one of the / pages on the site and using the View Source option of the browser, search for the __VIEWSTATE and notice that it is no longer a large encoded string, but a request number that is the key to the location of the viewstate for the page on the server. Conclusion This solution still supports the EnableViewState property for pages and controls and the viewstate size can be seen with tracing, this technique simply changes where the viewstate will be stored. The original driver of using Server Side ViewState was some corruption problems and lack of browser support for large hidden form fields. The use of the described technique solves both of those problems, while also reducing the page size sent to the client. ServerSideFiles.zip (2.44 kb)\n","date":"27 June 2008","externalUrl":null,"permalink":"/server-side-viewstate/","section":"Articles","summary":" Background ViewState is a feature provided by ASP.Net that stores information for server controls used on a web page. The primary advantage of this feature from a developer perspective is that it keeps the values of controls on a form. If the user forgot a single required field on a form, ASP.Net can put back the other values they had entered rather than forcing the developer to repopulate them. The information is encoded into a string and placed in a hidden form field called “__VIEWSTATE” that is sent to the client with the response (you can see this by using View Source in your browser when you view a / page). ASP.Net by default also calculates a “hash” of the information and adds it to the ViewState, then on a postback it can validate that the data has not been corrupted. That is a basic description of what viewstate is and how it is implemented, this article will focus on where the viewstate information is stored. ","title":"Server Side Viewstate","type":"articles"},{"content":"SQL Server provides both datatypes to store character information. For the most part the two datatypes are identical in how you would work with them within SQL Server or from an application. The difference is that nvarchar is used to store unicode data, which is used to store multilingual data in your database tables. Other languages have an extended set of character codes that need to be saved and this datatype allows for this extension. If your database will not be storing multilingual data you should use the varchar datatype instead. The reason for this is that nvarchar takes twice as much space as varchar, this is because of the need to store the extended character codes for other languages ","date":"27 June 2008","externalUrl":null,"permalink":"/nvarchar-versus-varchar/","section":"Articles","summary":"SQL Server provides both datatypes to store character information. For the most part the two datatypes are identical in how you would work with them within SQL Server or from an application. The difference is that nvarchar is used to store unicode data, which is used to store multilingual data in your database tables. Other languages have an extended set of character codes that need to be saved and this datatype allows for this extension. If your database will not be storing multilingual data you should use the varchar datatype instead. The reason for this is that nvarchar takes twice as much space as varchar, this is because of the need to store the extended character codes for other languages ","title":"NVARCHAR versus VARCHAR","type":"articles"},{"content":"I’ve been doing a little research on the use of an HTML Editor for development of internal project, using ASP.NET\nAloha Editor (http://www.aloha-editor.org)\nThis HTML editor is the bees knees, take a look at the website and check it out, it fantastic\nalohaeditor-0.23.9.zip (11.30 mb)\nFCKeditor (http://www.fckeditor.net/)\nThe editor is distributed under the GPL, LGPL and MPL open source licenses. This triple licensing model avoids incompatibility with other open source licenses, making it possible to integrate FCKeditor whenever you want.\nFreeTextBox (http://freetextbox.com/default/)\nFreeTextBox is the most-used HTML editor for ASP.NET. It is compatible with IE on the PC, and Mozilla and Firefox on all platforms. It is used in major Open Source projects such as Community Server and DotNetNuke as well as excellent packages like Smarter Mail. Buy FreeTextBox\nTo purchase a FreeTextBox Professional license or Distribution License with Source code, please click on one of the “Purchase” buttons below. Currently, PayPal is our payment provider. Once you click a “buy” you will be redirected to paypal where you can pay using your PayPal account or a credit card. Professional License – $49.99\nThe Professional License allows FreeTextBox to be used in all applications you or your company creates on as many servers as you host, but the license does not include rights to re-distribute FreeTextBox 3.0 Professional features in applications you or your company sell. If you sell or distribute products with FreeTextBox 3.0 Professional features, you must purchase a Distribution license (see below). Upon purchase, you will receive a unique FreeTextBox.lic file which will unlock the Professional features of FreeTextBox 3.0. Professional License Agreement\nTinyMCE (http://tinymce.moxiecode.com/index.php)\nOpen Source under LGPL\nCuteEditor (http://cutesoft.net/ASP.NET+WYSIWYG+Editor/default/)\nhttp://cutesoft.net/How+to+Buy/Licensing+Info/default/ This can be purchased from http://cutesoft.net/ASP.NET+WYSIWYG+Editor/Purchase+CuteEditor+for+.NET/default/\nRadEditor (http://www.telerik.com/products/aspnet-ajax/controls/editor/overview/)\nRadEditor for ASP.NET AJAX is the leading WYSIWYG web editor. It can replace any TextBox with an intuitive Word®-like editor, which enables even non-technical users to visually manage HTML content. Also available for SharePoint 2007 (MOSS) and DotNetNuke. Cost $999\nOn my research I could not find a BSD licensed HTML Editor.\nThe ones I have used before are RadEditor, very good, also very good support and backup. TinyMCE, very rich in features and easy to use. FCKeditor, little harder to use, and now with extra licences to allow for more general use ","date":"25 June 2008","externalUrl":null,"permalink":"/html-editor/","section":"Articles","summary":"I’ve been doing a little research on the use of an HTML Editor for development of internal project, using ASP.NET\nAloha Editor (http://www.aloha-editor.org)\nThis HTML editor is the bees knees, take a look at the website and check it out, it fantastic\n","title":"HTML Editor","type":"articles"},{"content":"This is the last part of an article series exploring reading and writing CSV files with C#/.NET. Part 1 covered converting the contents of a DataTable into CSV format. Part 2 explained how to read a CSV file back into a DataTable.\nFinally we will look at some test cases for use with NUnit, a very important tool that I'll describe in more detail in an upcoming article. There is quite a bit of code, but it is all very simple and easy to understand. Each method marked with [Test] will be called by NUnit and run one of the CSV related methods in turn. Assert statements will then check if the returned values are valid or not. First, let's check the parser methods. There are several tests here that all test something different; they all pass a CSV formatted string to the CsvParser.Parse method and check the returned DataTable. using System;\nusing System.Data;\nusing System.IO;\nusing NUnit.Framework; namespace CsvParser\n{\n[TestFixture]\npublic class TestCsvParser\n{\n[Test]\npublic void UnquotedLine()\n{\nDataTable table = CsvParser.Parse(\"one,two,three\");\nAssert.IsNotNull(table);\nAssert.AreEqual(3, table.Columns.Count);\nAssert.AreEqual(1, table.Rows.Count);\nAssert.AreEqual(\"one\", table.Rows[0][0]);\nAssert.AreEqual(\"two\", table.Rows[0][1]);\nAssert.AreEqual(\"three\", table.Rows[0][2]);\n}\n[Test]\npublic void QuotedLine()\n{\nDataTable table = CsvParser.Parse(\"\\\"one\\\",\\\"two\\\",\\\"three\\\"\");\nAssert.IsNotNull(table);\nAssert.AreEqual(3, table.Columns.Count);\nAssert.AreEqual(1, table.Rows.Count);\nAssert.AreEqual(\"one\", table.Rows[0][0]);\nAssert.AreEqual(\"two\", table.Rows[0][1]);\nAssert.AreEqual(\"three\", table.Rows[0][2]);\n}\n[Test]\npublic void TwoLines()\n{\nDataTable table = CsvParser.Parse(\"one,two,three\\nfour,five,six\\n\");\nAssert.IsNotNull(table);\nAssert.AreEqual(3, table.Columns.Count);\nAssert.AreEqual(2, table.Rows.Count);\nAssert.AreEqual(\"one\", table.Rows[0][0]);\nAssert.AreEqual(\"two\", table.Rows[0][1]);\nAssert.AreEqual(\"three\", table.Rows[0][2]);\nAssert.AreEqual(\"four\", table.Rows[1][0]);\nAssert.AreEqual(\"five\", table.Rows[1][1]);\nAssert.AreEqual(\"six\", table.Rows[1][2]);\n}\n[Test]\npublic void QuotedMultilineValue()\n{\nDataTable table = CsvParser.Parse(\n\"\\\"one\\n\\\"\\\"beer\\\"\\\"\\\",\\\"\\\"\\\"two\\\"\\\"\\nbeers\\\",\\\"three\\nbeers\\\"\");\nAssert.IsNotNull(table);\nAssert.AreEqual(3, table.Columns.Count);\nAssert.AreEqual(1, table.Rows.Count);\nAssert.AreEqual(\"one\\n\\\"beer\\\"\", table.Rows[0][0]);\nAssert.AreEqual(\"\\\"two\\\"\\nbeers\", table.Rows[0][1]);\nAssert.AreEqual(\"three\\nbeers\", table.Rows[0][2]);\n}\n[Test]\npublic void Headers()\n{\nDataTable table = CsvParser.Parse(\n\"First,Last,Email\\nAndreas,Knab,knabar@yahoo.com\", true);\nAssert.IsNotNull(table);\nAssert.AreEqual(3, table.Columns.Count);\nAssert.AreEqual(1, table.Rows.Count);\nAssert.AreEqual(\"Andreas\", table.Rows[0][\"First\"]);\nAssert.AreEqual(\"Knab\", table.Rows[0][\"Last\"]);\nAssert.AreEqual(\"knabar@yahoo.com\", table.Rows[0][\"Email\"]);\n}\n[Test]\npublic void TrailingNewlines()\n{\nDataTable table = CsvParser.Parse(\"test\\n\\n\\n\\n\\n\\n\");\nAssert.IsNotNull(table);\nAssert.AreEqual(1, table.Columns.Count);\nAssert.AreEqual(6, table.Rows.Count);\nAssert.AreEqual(\"test\", table.Rows[0][0]);\n}\n[Test]\npublic void Newlines()\n{\nDataTable table = CsvParser.Parse(\"test1\\x0Atest2\\x0Dtest3\\x0D\\x0Atest4\");\nAssert.IsNotNull(table);\nAssert.AreEqual(1, table.Columns.Count);\nAssert.AreEqual(4, table.Rows.Count);\nAssert.AreEqual(\"test1\", table.Rows[0][0]);\nAssert.AreEqual(\"test2\", table.Rows[1][0]);\nAssert.AreEqual(\"test3\", table.Rows[2][0]);\nAssert.AreEqual(\"test4\", table.Rows[3][0]);\n}\n}\n} Second, the opposite route – testing the CsvWriter. Since it takes quite a bit of effort to completely populate a DataTable, I'll cheat and create the DataTable using the CsvParser, which has been tested separately and is known to work.\nusing System;\nusing System.Data;\nusing System.IO;\nusing NUnit.Framework;\nusing CsvParser; namespace CsvWriter\n{\n[TestFixture]\npublic class TestCsvWriter\n{\n[Test]\npublic void PlainText()\n{\nstring s = \"one,two,three\\n\";\nDataTable table = CsvParser.Parse(s);\nstring t = CsvWriter.WriteToString(table, false, false);\nAssert.AreEqual(s, t);\n}\n[Test]\npublic void QuotedText()\n{\nstring s = \"\\\"one\\\",\\\"two\\\",\\\"three\\\"\\n\";\nDataTable table = CsvParser.Parse(s);\nstring t = CsvWriter.WriteToString(table, false, true);\nAssert.AreEqual(s, t);\n}\n[Test]\npublic void MultiLineText()\n{\nstring s = \"\\\"one\\nline\\\",\\\"two\\nline\\\",\\\"three\\nline\\\"\\n\";\nDataTable table = CsvParser.Parse(s);\nstring t = CsvWriter.WriteToString(table, false, false);\nAssert.AreEqual(s, t);\n}\n[Test]\npublic void Headers()\n{\nstring s = \"First,Last,Email\\nAndreas,Knab,knabar@yahoo.com\\n\";\nDataTable table = CsvParser.Parse(s, true);\nstring t = CsvWriter.WriteToString(table, true, false);\nAssert.AreEqual(s, t);\n}\n}\n} And that's it! There are more special cases that could be tested, especially invalid input like non-CSV files, but technically everything can be interpreted as CSV, so the question would be what output to expect.\nAs I mentioned earlier, NUnit is worth a closer look, so check back for more. ","date":"12 June 2008","externalUrl":null,"permalink":"/csv-file-parser-and-writer-in-c-part-3/","section":"Articles","summary":"This is the last part of an article series exploring reading and writing CSV files with C#/.NET. Part 1 covered converting the contents of a DataTable into CSV format. Part 2 explained how to read a CSV file back into a DataTable.\nFinally we will look at some test cases for use with NUnit, a very important tool that I'll describe in more detail in an upcoming article. There is quite a bit of code, but it is all very simple and easy to understand. Each method marked with [Test] will be called by NUnit and run one of the CSV related methods in turn. Assert statements will then check if the returned values are valid or not. ","title":"CSV file parser and writer in C# (Part 3)","type":"articles"},{"content":"This is the second part of an article series exploring reading and writing CSV files with C#/.NET. Part 1 covered converting the contents of a DataTable into CSV format; this part explains reading a CSV file back into a DataTable.\nFirst some namespace imports and the namespace declaration for this project: using System;\nusing System.Collections;\nusing System.Data;\nusing System.Text;\nusing System.IO; namespace CsvParser\n{ Like the CsvWriter class, all methods in the CsvParser class are static. There are four parser methods that return a DataTable from either a string or text stream, and expecting a header line in the CSV source or not. Only one method has a real body, all others just adjust their parameter signature. The implementation is simple: the method reads one \"row\" of the CSV source at a time and populates a row in the DataTable. The real meat is the private class CsvStream explained below. There is one utility method that returns an unused column name for a DataTable, in case there are no headers in the CSV source or the headers are not unique.\npublic class CsvParser\n{\npublic static DataTable Parse(string data, bool headers)\n{\nreturn Parse(new StringReader(data), headers);\n}\npublic static DataTable Parse(string data)\n{\nreturn Parse(new StringReader(data));\n} public static DataTable Parse(TextReader stream)\n{\nreturn Parse(stream, false);\n}\npublic static DataTable Parse(TextReader stream, bool headers)\n{\nDataTable table = new DataTable();\nCsvStream csv = new CsvStream(stream);\nstring[] row = csv.GetNextRow();\nif (row == null)\nreturn null;\nif (headers)\n{\nforeach (string header in row)\n{\nif (header != null \u0026amp;\u0026amp; header.Length \u0026gt; 0 \u0026amp;\u0026amp; !table.Columns.Contains(header))\ntable.Columns.Add(header, typeof(string));\nelse\ntable.Columns.Add(GetNextColumnHeader(table), typeof(string));\n}\nrow = csv.GetNextRow();\n}\nwhile (row != null)\n{\nwhile (row.Length \u0026gt; table.Columns.Count)\ntable.Columns.Add(GetNextColumnHeader(table), typeof(string));\ntable.Rows.Add(row);\nrow = csv.GetNextRow();\n}\nreturn table;\n}\nprivate static string GetNextColumnHeader(DataTable table)\n{\nint c = 1;\nwhile (true)\n{\nstring h = \"Column\" + c++;\nif (!table.Columns.Contains(h))\nreturn h;\n}\n} The CsvStream class does the actual work – read the CSV source in one character at a time and return meaningful chunks of decoded data, namely data items and rows.\nprivate class CsvStream\n{\nprivate TextReader stream; public CsvStream(TextReader s)\n{\nstream = s;\n} public string[] GetNextRow()\n{\nArrayList row = new ArrayList();\nwhile (true)\n{\nstring item = GetNextItem();\nif (item == null)\nreturn row.Count == 0 ? null : (string[])row.ToArray(typeof(string));\nrow.Add(item);\n}\n}\nprivate bool EOS = false;\nprivate bool EOL = false;\nprivate string GetNextItem()\n{\nif (EOL)\n{\n// previous item was last in line, start new line\nEOL = false;\nreturn null;\n}\nbool quoted = false;\nbool predata = true;\nbool postdata = false;\nStringBuilder item = new StringBuilder();\nwhile (true)\n{\nchar c = GetNextChar(true);\nif (EOS)\nreturn item.Length \u0026gt; 0 ? item.ToString() : null;\nif ((postdata || !quoted) \u0026amp;\u0026amp; c == ',')\n// end of item, return\nreturn item.ToString();\nif ((predata || postdata || !quoted) \u0026amp;\u0026amp; (c == '\\x0A' || c == '\\x0D'))\n{\n// we are at the end of the line, eat newline characters and exit\nEOL = true;\nif (c == '\\x0D' \u0026amp;\u0026amp; GetNextChar(false) == '\\x0A')\n// new line sequence is 0D0A\nGetNextChar(true);\nreturn item.ToString();\n}\nif (predata \u0026amp;\u0026amp; c == ' ')\n// whitespace preceeding data, discard\ncontinue;\nif (predata \u0026amp;\u0026amp; c == '\"')\n{\n// quoted data is starting\nquoted = true;\npredata = false;\ncontinue;\n}\nif (predata)\n{\n// data is starting without quotes\npredata = false;\nitem.Append(c);\ncontinue;\n}\nif (c == '\"' \u0026amp;\u0026amp; quoted)\n{\nif (GetNextChar(false) == '\"')\n// double quotes within quoted string means add a quote item.Append(GetNextChar(true));\nelse\n// end-quote reached\npostdata = true;\ncontinue;\n}\n// all cases covered, character must be data\nitem.Append(c);\n}\n}\nprivate char[] buffer = new char[4096];\nprivate int pos = 0;\nprivate int length = 0;\nprivate char GetNextChar(bool eat)\n{\nif (pos \u0026gt;= length)\n{\nlength = stream.ReadBlock(buffer, 0, buffer.Length);\nif (length == 0)\n{\nEOS = true;\nreturn '\\0';\n}\npos = 0;\n}\nif (eat)\nreturn buffer[pos++];\nelse\nreturn buffer[pos];\n}\n}\n}\n} And that's about it. In an upcoming part of this article I'll share some NUnit test cases for these classes. ","date":"12 June 2008","externalUrl":null,"permalink":"/csv-file-parser-and-writer-in-c-part-2/","section":"Articles","summary":"This is the second part of an article series exploring reading and writing CSV files with C#/.NET. Part 1 covered converting the contents of a DataTable into CSV format; this part explains reading a CSV file back into a DataTable.\n","title":"CSV file parser and writer in C# (Part 2)","type":"articles"},{"content":"An issue that comes up quite frequently is how to read and write comma seperated value (CSV) files in C#. Surprisingly the .NET libraries have no built-in support for this, and the usual solution to use an OleDb connection to the CSV file with Microsoft Excel's database driver is convoluted and not cross-platform. CSV files have a very simple structure (source): Each record is one line (with exceptions) Fields are separated with commas Leading and trailing space-characters adjacent to comma field separators are ignored Fields with embedded commas must be delimited with double-quote characters Fields that contain double quote characters must be surounded by double-quotes, and the embedded double-quotes must each be represented by a pair of consecutive double quotes. A field that contains embedded line-breaks must be surounded by double-quotes Fields with leading or trailing spaces must be delimited with double-quote characters Fields may always be delimited with double quotes The first record in a CSV file may be a header record containing column (field) names In this article, I'll provide simple, but fully functional code to read and write a CSV file according to these rules. In memory, data will be represented as a DataTable, which makes it easy to process; for storage in the file system or transfer over a network the CSV data will be stored as a String or in a Stream.\nFirst, the easy part: writing a DataTable to a CSV file. public class CsvWriter\n{\npublic static string WriteToString(DataTable table, bool header, bool quoteall)\n{\nStringWriter writer = new StringWriter();\nWriteToStream(writer, table, header, quoteall);\nreturn writer.ToString();\n} public static void WriteToStream(TextWriter stream, DataTable table, bool header, bool quoteall)\n{\nif (header)\n{\nfor (int i = 0; i \u0026lt; table.Columns.Count; i++)\n{\nWriteItem(stream, table.Columns[i].Caption, quoteall);\nif (i \u0026lt; table.Columns.Count – 1)\nstream.Write(',');\nelse\nstream.Write('\\n');\n}\n}\nforeach (DataRow row in table.Rows)\n{\nfor (int i = 0; i \u0026lt; table.Columns.Count; i++)\n{\nWriteItem(stream, row[i], quoteall);\nif (i \u0026lt; table.Columns.Count – 1)\nstream.Write(',');\nelse\nstream.Write('\\n');\n}\n}\n}\nprivate static void WriteItem(TextWriter stream, object item, bool quoteall)\n{\nif (item == null)\nreturn;\nstring s = item.ToString();\nif (quoteall || s.IndexOfAny(\"\\\",\\x0A\\x0D\".ToCharArray()) \u0026gt; –1)\nstream.Write(\"\\\"\" + s.Replace(\"\\\"\", \"\\\"\\\"\") + \"\\\"\");\nelse\nstream.Write(s);\n}\n}\nThe methods are static since the whole conversion is done in one method call, there is no need to create object instances etc.\nWriteToString will return the CSV file in a string; it is just a wrapper around the more generic WriteToStream method. Both methods take a DataTable and two boolean flags to indicate if you want to write a header line (which would use the column headers of the DataTable) and if you want to quote all values instead of only values that need to be quoted.\nSince CSV files do not work well for binary data, your DataTable should not contain any, although the resulting file would still be valid and could be read back in.\nWriteToStream just loops through all rows and columns of the DataTable and writes the individual data items to the output stream.\nThe WriteItem method finally encodes an individual data item and, if necessary or requested, adds quotes around it.\nIn upcoming parts of this article series, I'll provide and explain code to read a CSV file back into a DataTable, and how to use NUnit to test everything.\n","date":"12 June 2008","externalUrl":null,"permalink":"/csv-file-parser-and-writer-in-c-part-1/","section":"Articles","summary":"An issue that comes up quite frequently is how to read and write comma seperated value (CSV) files in C#. Surprisingly the .NET libraries have no built-in support for this, and the usual solution to use an OleDb connection to the CSV file with Microsoft Excel's database driver is convoluted and not cross-platform. CSV files have a very simple structure (source): Each record is one line (with exceptions) Fields are separated with commas Leading and trailing space-characters adjacent to comma field separators are ignored Fields with embedded commas must be delimited with double-quote characters Fields that contain double quote characters must be surounded by double-quotes, and the embedded double-quotes must each be represented by a pair of consecutive double quotes. A field that contains embedded line-breaks must be surounded by double-quotes Fields with leading or trailing spaces must be delimited with double-quote characters Fields may always be delimited with double quotes The first record in a CSV file may be a header record containing column (field) names In this article, I'll provide simple, but fully functional code to read and write a CSV file according to these rules. In memory, data will be represented as a DataTable, which makes it easy to process; for storage in the file system or transfer over a network the CSV data will be stored as a String or in a Stream.\n","title":"CSV file parser and writer in C# (Part 1)","type":"articles"},{"content":"","date":"30 May 2008","externalUrl":null,"permalink":"/categories/blogengine.net/","section":"Categories","summary":"","title":"BlogEngine.NET","type":"categories"},{"content":"So I keep running into the same problem – I am building a small website for somebody and I need to provide them with a way to update the content of their site so I don’t have to. Basically, I need a lightweight and flexible content management system that is easy to use.\nIf The Shoe Fits… When I first thought of a lightweight CMS, I thought of graffiti. It sounds like exactly what I need. So I downloaded the express edition and started evaluating it. It seemed like a nice product and all is not free for commercial use ($399 is the cheapest commercial licence) and I can’t afford that price tag when building small websites.\nEnter BlogEngine.net. My favorite blogging platform. There, I said it. Well, I use it to run my blog and I am constantly tinkering around with the site all of the time because I enjoy using BlogEngine.net so much.\nI thought that BlogEngine.net has all of the key pieces I needed for my lightweight CMS:\nA WYSIWYG Editor A Metaweblog interface Tons of extensibility Basic Idea I decided to base my CMS implementation on the concept of pages. Most blog engines have two distinct types of content: pages and posts. Posts are the typical type of content that becomes part of your blogs feed whereas pages are usually static content which can be anything outside of a blog post (for example an ‘About Me’ page). BlogEngine.net already has everything I need to get the content of page created and persisted in a data store (it supports xml and sql server out of the box). I decided to write a web control which I can place on any webpage and include the contents of a given page from the data store.\nI made a control called PageViewer which you can place on the page like this:\n\u0026lt;blog:PageViewer ID=“view” runat=“server” DisplayTitle=“false” PageId=“167eb7f3-135b-4f90-9756-be25ec10f14c” /\u0026gt; This control basically just looks up the page using the given id (this functionality is all provided by the existing BlogEngine.Core library) and displays its content. Here is the rendering logic\nif (PageId != Guid.Empty)\tpage = BlogEngine.Core.Page.GetPage(PageId);if (page != null){\tServingEventArgs arg = new ServingEventArgs(page.Content,ServingLocation.SinglePage);BlogEngine.Core.Page.OnServing(page, arg);\tif (arg.Cancel)\tPage.Response.Redirect(\"error404/\", true);\tif (DisplayTitle)\t{\twriter.Write(\"\u0026lt;h1\u0026gt;\");\twriter.Write(page.Title);\twriter.Write(\"\u0026lt;/h1\u0026gt;\");\t}\twriter.Write(\"\u0026lt;div\u0026gt;\");\twriter.Write(arg.Body);\twriter.Write(\"\u0026lt;/div\u0026gt;\");} This code is pretty straight forward – all it does is get an instance of the page and then display its title in \u0026lt;h1\u0026gt; a tag and its body in \u0026lt;div\u0026gt; tag. This logic is actually straight from the existing page retrieval code that already exists in BlogEngine.net. This web control is pretty much the only new code I had to write. The rest of the project mostly involves moving files around and removing parts of the BlogEngine.net framework that I don’t need.\nArmed with this control, we are ready to start converting the static pages from the old version of the website to be BlogEngine.net pages which can be stored and retrieved using the BlogEngine.Core classes.\nThemes\nIt’s also worth noting that there are many themes available for BlogEngine\nthemes4blogengine.net ","date":"30 May 2008","externalUrl":null,"permalink":"/using-blogengine-net-as-a-general-purpose-content-management-system/","section":"Articles","summary":"So I keep running into the same problem – I am building a small website for somebody and I need to provide them with a way to update the content of their site so I don’t have to. Basically, I need a lightweight and flexible content management system that is easy to use.\n","title":"Using BlogEngine.net as a General Purpose Content Management System","type":"articles"},{"content":" I've been after creating a Wiki for some time, and I think I may have found one worth looking at 'Screw Turn', not the most inspiring name but I have read good reviews, so I'll be having a look in my spare time at what it can do and how I can implement it www.screwturn.eu ","date":"27 May 2008","externalUrl":null,"permalink":"/wiki/","section":"Articles","summary":" I've been after creating a Wiki for some time, and I think I may have found one worth looking at 'Screw Turn', not the most inspiring name but I have read good reviews, so I'll be having a look in my spare time at what it can do and how I can implement it www.screwturn.eu ","title":"Wiki","type":"articles"},{"content":" My Latests Resume is now available online in both HTML and Word format Click here to see what I've been doing!\n","date":"26 May 2008","externalUrl":null,"permalink":"/resume-now-available-online/","section":"Articles","summary":" My Latests Resume is now available online in both HTML and Word format Click here to see what I've been doing!\n","title":"Resume now available online","type":"articles"},{"content":" DIRECTIONS TO THE 31 The Pound, Bromham, SN15 2HE View Larger Map From where-ever you start drive to Junction 17 of M4 THE FOLLOWING WILL ONLY TAKE YOU ABOUT 15 MINS! Take the A350 to Chippenham (Mostly Dual Carriageway) Services on 1st roundabout and keep following signs ‘A350 Chippenham’ Lots of rounabouts Reach Roundabout turn left following signs for Chippenham/Devizes this roundabout has Sainsburys on your left (its quite hidden) Drive through housing area with lots of roundabouts (your going round outskirts of chippenham) Reach roundabout with ‘Town Centre left’ and ‘Devizes right’, turn right. Drive pass small petrol station and a pub turn turn right up hill ‘A342 Devizes’ Go up hill pass ‘Bowood Country Club’ on your left Follow road through ‘Sandy Lane’ with lovely thatch cottages Road becomes v straight again with sign post ‘Melksham right’ DON’T turn right! Keep straight on Almost there so slow down, a few bends, sign post turn right BROMHAM Drive pass tennis courts on right with kids play area – keep slow! Set of trees on right, Bryans house is 1st house on right IT’S QUITE HIDDEN! Turn right and park ","date":"9 October 2007","externalUrl":null,"permalink":"/directions-to-coppermill/","section":"Articles","summary":" DIRECTIONS TO THE 31 The Pound, Bromham, SN15 2HE View Larger Map From where-ever you start drive to Junction 17 of M4 THE FOLLOWING WILL ONLY TAKE YOU ABOUT 15 MINS! Take the A350 to Chippenham (Mostly Dual Carriageway) Services on 1st roundabout and keep following signs ‘A350 Chippenham’ Lots of rounabouts Reach Roundabout turn left following signs for Chippenham/Devizes this roundabout has Sainsburys on your left (its quite hidden) Drive through housing area with lots of roundabouts (your going round outskirts of chippenham) Reach roundabout with ‘Town Centre left’ and ‘Devizes right’, turn right. Drive pass small petrol station and a pub turn turn right up hill ‘A342 Devizes’ Go up hill pass ‘Bowood Country Club’ on your left Follow road through ‘Sandy Lane’ with lovely thatch cottages Road becomes v straight again with sign post ‘Melksham right’ DON’T turn right! Keep straight on Almost there so slow down, a few bends, sign post turn right BROMHAM Drive pass tennis courts on right with kids play area – keep slow! Set of trees on right, Bryans house is 1st house on right IT’S QUITE HIDDEN! Turn right and park ","title":"Directions to Coppermill","type":"articles"},{"content":"Found these great articles on LINQ to SQL, well worth reading as it the way to go forwards\nUsing LINQ to SQL (Part 1) LINQ to SQL (Part 2 – Defining our Data Model Classes) LINQ to SQL (Part 3 – Querying our Database) ","date":"9 July 2007","externalUrl":null,"permalink":"/using-linq-to-sql/","section":"Articles","summary":"Found these great articles on LINQ to SQL, well worth reading as it the way to go forwards\nUsing LINQ to SQL (Part 1) LINQ to SQL (Part 2 – Defining our Data Model Classes) LINQ to SQL (Part 3 – Querying our Database) ","title":"Using LINQ to SQL","type":"articles"},{"content":"edream.org Blog Article Extending Personal Web Site Starter Kit (3) spammer-proof email address ","date":"27 February 2007","externalUrl":null,"permalink":"/spammer-proof-email-address/","section":"Articles","summary":"edream.org Blog Article Extending Personal Web Site Starter Kit (3) spammer-proof email address ","title":"spammer-proof email address","type":"articles"},{"content":"It's that time again, when Microsoft are going to get everyone to move and upgrade to another operating system, and I've been so happy with XP, I'm going to need a bit of convincing to move over.\nJust in case I do here is some information to help me along.\nDownload details: Windows Vista Step-by-Step Guides for IT Professionals: \"Windows Vista\" ","date":"26 February 2006","externalUrl":null,"permalink":"/download-details-windows-vista-step-by-step-guides-for-it-professionals/","section":"Articles","summary":"It's that time again, when Microsoft are going to get everyone to move and upgrade to another operating system, and I've been so happy with XP, I'm going to need a bit of convincing to move over.\n","title":"Download details: Windows Vista Step-by-Step Guides for IT Professionals","type":"articles"},{"content":"Useful little short cut to allow you to run / login as another process as a different user without having to logoff and back in again. %windir%\\system32\\runas.exe /profile /user:gwtest\\testuser /savecred \"c:\\program files\\internet explorer\\iexplore.exe\" ","date":"22 December 2005","externalUrl":null,"permalink":"/how-to-run-an-application-as-another-user/","section":"Articles","summary":"Useful little short cut to allow you to run / login as another process as a different user without having to logoff and back in again. %windir%\\system32\\runas.exe /profile /user:gwtest\\testuser /savecred \"c:\\program files\\internet explorer\\iexplore.exe\" ","title":"How to run an application as another user","type":"articles"},{"content":" Concurrent Remote Desktop Sessions in Windows XP SP2 I mentioned before that Windows XP does not allow concurrent sessions for its Remote Desktop feature. What this means is that if a user is logged on at the local console, a remote user has to kick him off (and ironically, this can be done even without his permission) before starting work on the box. This is irritating and removes much of the productivity that Remote Desktop brings to Windows. Read on to learn how to remove that limitation in Windows XP SP2 A much touted feature in SP2 (Service Pack 2) since then removed was the ability to do just this, have a user logged on locally while another connects to the terminal remotely. Microsoft however removed the feature in the final build. The reason probably is that the EULA (End User License Agreement) allows only a single user to use a computer at a time. This is (IMHO) a silly reason to curtail Remote Desktop's functionality, so we'll have a workaround. Microsoft did try out the feature in earlier builds of Service Pack 2 and it is this that we're going to exploit here. We're going to replace termserv.dll (The Terminal Server) with one from an earlier build (2055). To get Concurrent Sessions in Remote Desktop working, follow the steps below exactly: Download the termserv.zip file below and extract it somewhere. (You have to be registered to see the file) Reboot into Safe Mode. This is necessary to remove Windows File Protection. Copy the termserv.dll in the zip to %windir%\\System32 and %windir%\\ServicePackFiles\\i386. If the second folder doesn't exist, don't copy it there. Delete termserv.dll from the dllcache folder: %windir%\\system32\\dllcache Merge the contents of Concurrent Sessions SP2.reg file into the registry. Make sure Fast User Switching is turned on. Go Control Panel -\u0026gt; User Accounts -\u0026gt; Change the way users log on or off and turn on Fast User Switching. Open up the Group Policy Editor: Start Menu \u0026gt; Run \u0026gt; 'gpedit.msc'. Navigate to Computer Configuration \u0026gt; Administrative Templates \u0026gt; Windows Components \u0026gt; Terminal Services. Enable 'Limit Number of Connections' and set the number of connections to 3 (or more). This enables you to have more than one person remotely logged on. Now reboot back into normal Windows and try out whether Concurrent Sessions in Remote Desktop works. It should! If anything goes wrong, the termserv_sp2.dll is the original file you replaced. Just rename it to termserv.dll, reboot into safe mode and copy it back. The termserv.dl_ file is provided in the zip is for you slipstreamers out there. Just replace that file with the corresponding file in the Windows installation disks. I've added in extra information from the comments below… thanks for all who researched! 🙂 http://sig9.com/node/110 ","date":"15 November 2005","externalUrl":null,"permalink":"/concurrent-remote-sessions-in-xp/","section":"Articles","summary":" Concurrent Remote Desktop Sessions in Windows XP SP2 I mentioned before that Windows XP does not allow concurrent sessions for its Remote Desktop feature. What this means is that if a user is logged on at the local console, a remote user has to kick him off (and ironically, this can be done even without his permission) before starting work on the box. This is irritating and removes much of the productivity that Remote Desktop brings to Windows. Read on to learn how to remove that limitation in Windows XP SP2 A much touted feature in SP2 (Service Pack 2) since then removed was the ability to do just this, have a user logged on locally while another connects to the terminal remotely. Microsoft however removed the feature in the final build. The reason probably is that the EULA (End User License Agreement) allows only a single user to use a computer at a time. This is (IMHO) a silly reason to curtail Remote Desktop's functionality, so we'll have a workaround. Microsoft did try out the feature in earlier builds of Service Pack 2 and it is this that we're going to exploit here. We're going to replace termserv.dll (The Terminal Server) with one from an earlier build (2055). To get Concurrent Sessions in Remote Desktop working, follow the steps below exactly: Download the termserv.zip file below and extract it somewhere. (You have to be registered to see the file) Reboot into Safe Mode. This is necessary to remove Windows File Protection. Copy the termserv.dll in the zip to %windir%\\System32 and %windir%\\ServicePackFiles\\i386. If the second folder doesn't exist, don't copy it there. Delete termserv.dll from the dllcache folder: %windir%\\system32\\dllcache Merge the contents of Concurrent Sessions SP2.reg file into the registry. Make sure Fast User Switching is turned on. Go Control Panel -\u003e User Accounts -\u003e Change the way users log on or off and turn on Fast User Switching. Open up the Group Policy Editor: Start Menu \u003e Run \u003e 'gpedit.msc'. Navigate to Computer Configuration \u003e Administrative Templates \u003e Windows Components \u003e Terminal Services. Enable 'Limit Number of Connections' and set the number of connections to 3 (or more). This enables you to have more than one person remotely logged on. Now reboot back into normal Windows and try out whether Concurrent Sessions in Remote Desktop works. It should! If anything goes wrong, the termserv_sp2.dll is the original file you replaced. Just rename it to termserv.dll, reboot into safe mode and copy it back. The termserv.dl_ file is provided in the zip is for you slipstreamers out there. Just replace that file with the corresponding file in the Windows installation disks. I've added in extra information from the comments below… thanks for all who researched! 🙂 http://sig9.com/node/110 ","title":"Concurrent Remote Sessions in XP","type":"articles"},{"content":"[lightbox:/uploads/2008/11/ViewfromtheChurch.jpg]\n","date":"1 November 2001","externalUrl":null,"permalink":"/lightbox-example/","section":"Articles","summary":"[lightbox:/uploads/2008/11/ViewfromtheChurch.jpg]\n","title":"Lightbox Example","type":"articles"},{"content":" Why I write # This website is my technical notebook. Some posts are quick references to a problem I\u0026rsquo;ve solved. Others explore the bigger questions around architecture, cloud, security, AI and how teams build software together.\nI started writing about .NET and web development many years ago. The technologies have changed, but my interest is much the same: how do we build things that work well, stay secure and remain understandable to the people looking after them?\nThere’s more to life than software # Open-water swimming is a big part of my life. I\u0026rsquo;m also involved in SwimTayka, a charity helping children develop swimming and water-safety skills. It is a useful reminder that the best work often comes down to people, purpose and getting the basics right.\n","externalUrl":null,"permalink":"/about-me/","section":"Bryan Avery","summary":"Why I write # This website is my technical notebook. Some posts are quick references to a problem I’ve solved. Others explore the bigger questions around architecture, cloud, security, AI and how teams build software together.\n","title":"About me","type":"about"},{"content":"\nhttps://learn.microsoft.com/api/credentials/share/en-gb/BryanAvery/1C0E901C5311A657?sharingId=464139BD4EB8826F\nhttps://learn.microsoft.com/api/credentials/share/en-gb/BryanAvery-9106/303A9DC233C1825E?sharingId=464139BD4EB8826F\nhttps://learn.microsoft.com/en-gb/users/bryanavery-9106/credentials/2c8d12775cab5295\nhttps://learn.microsoft.com/api/credentials/share/en-gb/BryanAvery-9106/7BEC20F1D5131366?sharingId=464139BD4EB8826F\nhttps://learn.microsoft.com/api/credentials/share/en-gb/BryanAvery/C19EB3718787867C?sharingId=464139BD4EB8826F\n","externalUrl":null,"permalink":"/microsoft-certified/","section":"Bryan Avery","summary":"\nhttps://learn.microsoft.com/api/credentials/share/en-gb/BryanAvery/1C0E901C5311A657?sharingId=464139BD4EB8826F\nhttps://learn.microsoft.com/api/credentials/share/en-gb/BryanAvery-9106/303A9DC233C1825E?sharingId=464139BD4EB8826F\nhttps://learn.microsoft.com/en-gb/users/bryanavery-9106/credentials/2c8d12775cab5295\n","title":"Microsoft Certified","type":"page"},{"content":"This is an archived CV. It reflects previous roles and experience rather than a current employment summary.\nclick here to download my Word version of the Bryan Avery Resume \u0026#8211; Lead Developer\nclick here for the PDF Resume for Bryan Avery \u0026#8211; Lead Developer\nPersonal Profile\nI am a hands-on, SME (Subject Matter Expert) in the full development lifecycle, Microsoft C# developer using Azure and MVC as my preferred tools.\nI have worked with Microsoft technologies for over 20 years building software for some of the world’s leading private and public sector companies, applying both technical knowledge and managerial expertise. My preferred technology stack includes C#, Azure, MVC, Entity Framework and SQL Server. I also know VB.NET, and I’m not afraid to use it!\nAn integral part of my work is to provide my clients with a high standard of understandable technical documentation: I have written white papers, technical specifications, designs, as well as User Guides. I was the technical reviewer for the “Pro ASP.NET MVC Framework (Expert\u0026#8217;s Voice in .NET)” publication (http://tinyurl.com/MVCFramework) by Apress.\nUsing Azure for over 5 years, with 3 years commercial experience, migrating application to the cloud, fully managed continuous integration for all environments.\nI have on many occasions provided technical lectures at universities and user groups on topics such as Azure, IoC, Agile Development, NBuilder, Balsamiq Mockups, and the World of the Internet\nMy technical ability:\nC# .NET 10+ years Azure 6 years MVC 7 years ASP.NET 9 years Entity Framework 3 years SQL Server 7 years IoC 4 years Team Foundation Server 4 years Test Driven Development 3 years PEN Testing 1 year In my spare time, I keep fit taking part in triathlons and long distance swimming and run a swimming charity (http://SwimTayka.org). I recently swam the English Channel to France, swam 30 miles around Manhattan Island and another 30 miles across the Catalina Channel to L.A. In 2006 I completed an Ironman competition in Nice, France.\nPixelPin May 2017 – June 2017\nTechnical Team Leader and Developer in Security\nI was working on two projects an Encryptor library and Azure automated deployment (ARM).\nThe first project was to safeguard cryptographic keys and other secrets on services used within side PixelPin’s environment. I provided and developed an increased security and control over keys and passwords along with using an application to ensure there is no direct access for any staff to the cryptographic keys.\nI made a single entry point for all the security and provided a standard pattern that is much slicker and quicker than the OWASP Enterprise Security API but still using the core foundations of its interface to ensure backwards compatibility.\nDeveloped and built a Secure KeyStore to store encryption keys and small secrets like passwords. The KeyStore allowed for different storage locations, and this included everything from secure memory storage, SQL Server or Hardware Security Modules (HSM’s) using the Azure Key Vault.\nThe second project provided automatic configuration services and scaled those services based on a customer\u0026#8217;s demands. To do this, I built the process using the Azure Resource Manager (ARM) Templates. The deployment of App Services, Redis, SQL Servers, App Insights, CDN’s and Storage Accounts were all part of this implementation. The goal was to have the ability to limit the number of clicks required to deploy to an environment within the Microsoft Azure Cloud platform. Provided an automated deployment process which took 20 minutes as opposed to 4 hours of manual building. This automation was used for live deployments to new geo-locations and enable the testers to build a test environment that represents the live environment as closely as possible.\nMy skills employed here:\nC# 7 Encryption (AES, RSA, DSA etc) Azure Azure Key Vault MS SQL (Azure) DocumentDB Azure Templates BitBucket JIRA BCS (British Computer Society) October 2016 – current date\nSME – Subject Matter Expert\nI provide professional advice and consultancy over the complete Software Development Lifecycle, in the production of examination questions which included the following areas:\nBusiness Context and Market Environment Software Development Methodologies Team Roles and Relationships Application Structure and Development Platform Context Software Testing Configuration Management and Version Control Systems The end-user context for software development activities How code integrates into the wider project Developing software against a set of functional and non-functional requirements Implement software code following a logical approach Code against data sources Follow good coding practices Understand the principles of good interface design Security in software development Systopia October 2016 – May 2017\nTechnical Team Leader and Developer\nBuilding and developing a reporting system to allow catering customers to view metrics and information on the usage of machines held on customer’s sites.\nThis was an MVC application, using Telerik controls to provide graphics and reports for the customers.\nManaging and building of a facade application that is loaded onto the Kiosk at catering companies offices. This not only provided a secure environment but also gave Systopia the flexibility of reusing the application for other customers. Each kiosk application talked to a central secure REST API service that provided all the configuration information for that Kiosk giving full control of the Kiosk from a remote location.\ntalentcubed July 2014 \u0026#8211; September 2016\nTeam Leader / Azure Consultant\nhttp://www.talentcubed.com\nStart-up business produced a social network platform dedicated to connecting businesses with university students. Currently, here are over 20,000 students using the website in universities around the country.\nI headed up a development team from India to build the prototype, then I migrated the skills back to England to produce an MVC 5, C#, WCF, SQL application running fully on Microsoft’s Azure platform. With so many people using the website it was essential that full PEN testing was implemented to protect from Hackers.\nAll the environments used the Cloud, this included development, source control (TFS), project management, and the three platforms, Live, Test and Development, all with Continuous Integration using TFS, to allow easy to deploy applications. My skills employed here:\nC# 4.5 MVC 5 WCF Azure Websites Azure Mobile Services Azure SQL Azure Storage (Blobs) Azure Virtual Machines for development Visual Studio Online PEN Testing BCS (British Computer Society) August 2013 – June 2014\nLead Senior Developer / Architecture Consultant\nRepeat work for BCS (September 2008 – 2009) as they requested I come back to work for them again.\nWorking on improving the client’s website to allow for general public access to allow them to sign up for examinations and tests. As lessons were limited, the end user would have a limited time to complete the application form and register for a course.\nThis involved working with the analyst teams, management and testers to ensure that not only the new functionality was implemented, but also the existing workflow still continued to work fully.\nMy skills employed here\nC# 4.5 MVC 5 Azure Websites MS SQL Azure Virtual Machines for development End user Testing ","externalUrl":null,"permalink":"/resume/","section":"Bryan Avery","summary":"This is an archived CV. It reflects previous roles and experience rather than a current employment summary.\nclick here to download my Word version of the Bryan Avery Resume – Lead Developer\nclick here for the PDF Resume for Bryan Avery – Lead Developer\n","title":"Resume","type":"page"},{"content":"","externalUrl":null,"permalink":"/tags/","section":"Tags","summary":"","title":"Tags","type":"tags"}]