Running ASP.NET Webforms and ASP.NET MVC side by side
One of the nice things about ASP.NET MVC and its older brother ASP.NET WebForms is that they are both built on top of the ASP.NET runtime environment. The advantage of this is that, you can still run them side by side even though MVC and WebForms are different frameworks. Another point to note is that with the release of the ASP.NET routing in .NET 3.5 SP1, we are able to create SEO friendly URLs that do not map to specific files on disk. The routing is part of the core runtime environment and therefore can be used by both WebForms and MVC. To run both frameworks side by side, we could easily create a separate folder in your MVC project for all our WebForm files and be good to go. What this post shows you instead, is how to have an MVC application with WebForm pages that both use a common master page and common routing for SEO friendly URLs. A sample project that shows WebForms and MVC running side by side is attached at the bottom of this post. So why would we want to run WebForms and MVC in the same project? WebForms come with a lot of server controls that provide a lot of rich functionality. One example is the ReportViewer control. Using this control and client report definition files (RDLC), we can create rich interactive reports (with charting controls). I show you how to use the ReportViewer control in a WebForm project here : Creating an ASP.NET report using Visual Studio 2010. We can create even more advanced reports by using SQL reporting services that can also be rendered by the ReportViewer control. Moving along, consider the sample MVC application I blogged about titled : ASP.NET MVC Paging/Sorting/Filtering using the MVCContrib Grid and Pager. Assume you were given the requirement to add a UI to the MVC application where users could interact with a report and be given the option to export the report to Excel, PDF or Word. How do you go about doing it? This is a perfect scenario to use the ReportViewer control and RDLCs. As you saw in the post on creating the ASP.NET report, the ReportViewer control is a Web Control and is designed to be run in a WebForm project with dependencies on, amongst others, a ScriptManager control and the beloved Viewstate. Read more: Raj Kaimal
Microsoft Access 2010 Source Code Control
Posted by
jasper22
at
11:43
|
The Microsoft Access 2010 Source Code Control makes it easy to deploy and manage solutions built using Microsoft Access.Read more: MS Download
Integrating HTML into Silverlight Applications
Posted by
jasper22
at
11:42
|
Looking for a way to display HTML content within a Silverlight application? If you haven’t tried doing that before it can be challenging at first until you know a few tricks of the trade. Being able to display HTML is especially handy when you’re required to display RSS feeds (with embedded HTML), SQL Server Reporting Services reports, PDF files (not actually HTML – but the techniques discussed will work), or other HTML content. In this post I'll discuss three options for displaying HTML content in Silverlight applications and describe how my company is using these techniques in client applications. Displaying HTML Overlays
If you need to display HTML over a Silverlight application (such as an RSS feed containing HTML data in it) you’ll need to set the Silverlight control’s windowless parameter to true. This can be done using the object tag as shown next: By setting the control to “windowless” you can overlay HTML objects by using absolute positioning and other CSS techniques. Keep in mind that on Windows machines the windowless setting can result in a performance hit when complex animations or HD video are running since the plug-in content is displayed directly by the browser window. It goes without saying that you should only set windowless to true when you really need the functionality it offers. For example, if I want to display my blog’s RSS content on top of a Silverlight application I could set windowless to true and create a user control that grabbed the content and output it using a DataList control: <style type="text/css">
a {text-decoration:none;font-weight:bold;font-size:14pt;}
</style>
<div style="margin-top:10px; margin-left:10px;margin-right:5px;">
<asp:DataList ID="RSSDataList" runat="server" DataSourceID="RSSDataSource">
<ItemTemplate>
<br />
<%# XPath("description") %>
<br />
</ItemTemplate>
</asp:DataList>
<asp:XmlDataSource ID="RSSDataSource" DataFile="http://weblogs.asp.net/dwahlin/rss.aspx"
XPath="rss/channel/item" CacheDuration="60" runat="server" />
</div>The user control can then be placed in the page hosting the Silverlight control as shown below. This example adds a Close button, additional content to display in the overlay window and the HTML generated from the user control. <div id="RSSDiv">
<div style="background-color:#484848;border:1px solid black;height:35px;width:100%;">
<img alt="Close Button" align="right" src="Images/Close.png" onclick="HideOverlay();" style="cursor:pointer;" />
</div>
<div style="overflow:auto;width:800px;height:565px;">
<div style="float:left;width:100px;height:103px;margin-left:10px;margin-top:5px;">
<img src="
" style="border:1px solid Gray" />
</div>
<div style="float:left;width:300px;height:103px;margin-top:5px;">
Dan Wahlin's Blog
</div>
<br /><br /><br />
<div style="clear:both;margin-top:20px;">
<uc:BlogRoller ID="BlogRoller" runat="server" />
</div>
</div>
</div>Of course, we wouldn’t want the RSS HTML content to be shown until requested. Once it’s requested the absolute position of where it should show above the Silverlight control can be set using standard CSS styles. The following ID selector named #RSSDiv handles hiding the overlay div shown above and determines where it will be display on the screen. Read more: Dan Wahlin's WebLog
If you need to display HTML over a Silverlight application (such as an RSS feed containing HTML data in it) you’ll need to set the Silverlight control’s windowless parameter to true. This can be done using the object tag as shown next: By setting the control to “windowless” you can overlay HTML objects by using absolute positioning and other CSS techniques. Keep in mind that on Windows machines the windowless setting can result in a performance hit when complex animations or HD video are running since the plug-in content is displayed directly by the browser window. It goes without saying that you should only set windowless to true when you really need the functionality it offers. For example, if I want to display my blog’s RSS content on top of a Silverlight application I could set windowless to true and create a user control that grabbed the content and output it using a DataList control: <style type="text/css">
a {text-decoration:none;font-weight:bold;font-size:14pt;}
</style>
<div style="margin-top:10px; margin-left:10px;margin-right:5px;">
<asp:DataList ID="RSSDataList" runat="server" DataSourceID="RSSDataSource">
<ItemTemplate>
<br />
<%# XPath("description") %>
<br />
</ItemTemplate>
</asp:DataList>
<asp:XmlDataSource ID="RSSDataSource" DataFile="http://weblogs.asp.net/dwahlin/rss.aspx"
XPath="rss/channel/item" CacheDuration="60" runat="server" />
</div>The user control can then be placed in the page hosting the Silverlight control as shown below. This example adds a Close button, additional content to display in the overlay window and the HTML generated from the user control. <div id="RSSDiv">
<div style="background-color:#484848;border:1px solid black;height:35px;width:100%;">
<img alt="Close Button" align="right" src="Images/Close.png" onclick="HideOverlay();" style="cursor:pointer;" />
</div>
<div style="overflow:auto;width:800px;height:565px;">
<div style="float:left;width:100px;height:103px;margin-left:10px;margin-top:5px;">
<img src="
" style="border:1px solid Gray" /></div>
<div style="float:left;width:300px;height:103px;margin-top:5px;">
Dan Wahlin's Blog
</div>
<br /><br /><br />
<div style="clear:both;margin-top:20px;">
<uc:BlogRoller ID="BlogRoller" runat="server" />
</div>
</div>
</div>Of course, we wouldn’t want the RSS HTML content to be shown until requested. Once it’s requested the absolute position of where it should show above the Silverlight control can be set using standard CSS styles. The following ID selector named #RSSDiv handles hiding the overlay div shown above and determines where it will be display on the screen. Read more: Dan Wahlin's WebLog
Moving Data from SQL Server 2000 to SQL Server 2008
Posted by
jasper22
at
11:42
|
I recently helped move data from a small SQL Sever 2000 database to SQL Server 2008 from one hosting environment to a different hosting environment. I tried several approaches and fortunately found one that worked well. You can find the detail in the post. Approach #1: SQL Server Import/Export WizardPeople who were familiar with SQL Server 2000 probably enjoyed the Import and Export wizard that came with SQL Server 2000 Enterprise Manager. I used it all the times to upload a local database to a hosted server and vice versa. The wizard did exactly what it was designed for. However, this wizard doesn’t work with SQL Server 2005 or 2008. In order to import/export or copy an entire database, you will need a different tool available to SQL Server 2005/2008. This tool (DTSWizard.exe) in SQL Server Management Studio allows you to copy data from tables and views only; it doesn’t import/export other objects such as stored procedures. Therefore, this option didn’t work for what I wanted to do. 
Read more: Dr. Z's Blog

Read more: Dr. Z's Blog
Build Tools Roundup For .NET Systems
Posted by
jasper22
at
11:39
|
It seems there is not shortage of build tools that are available for the .NET developer these days. Of course I’m quite partial to the Ruby + Rake + Albacore solution, being the big tuna behind albacore and all… but quite honestly that amount of choice makes me very happy. It seems there is a good tool for just about every different comfort zone in the .NET developer world. At this point in time, there’s not one right answer of which build tool to use. You don’t need to choose which tool to use based on what features and functionality it supports anymore. Rather, you can make the choices based on what your comfortable with – be it the runtime environment, the language to create build steps, the data specification, etc. Choice is good. Understanding what each choice offers is even better. Here’s my take on the current set of tools that I’m aware of and what the comfort zone of these tools are. Nant: The Godfather Of .NET Build SystemsRuntime: .NET
Build Configuration Language: XML with extensions written in .NET
URL: http://nant.sourceforge.net/ Nant is the old-school guy on the .NET block, having grown up over on Java road. This is the original .NET build tool that so many others wanted to be or wanted to be better than. If you’ve used any build tools for more than a few years in .NET, you’ve probably used Nant at least once. There are a lot of extensions and add-ons to Nant, including a user contributions project, several visual tools designed to abstract away the xml, some conventions based add-ons that make nant easier, etc. If you need to do it in your build process, chances are there is a plugin or a blog post that tells you how to do it with Nant. Nant was originally a copy of the Java Ant build tool but quickly took its own directions in implementation becoming the defacto build tool in .NET for several years. With it’s heavy reliance on xml and its roots tracing back to java, most “enterprise” developers chose Nant because of it’s familiarity from the Java world. Example: Build a solution 1: <target name="compile">
2: <echo message="Build my solution!" />
3: <msbuild project="src/mysolution.sln">
4: <arg value="/property:Configuration=release" />
5: <arg value="/t:Rebuild" />
6: </msbuild>
7: </target>
UppercuT: You Won’t Know What Hit YouRuntime: .NET (Nant) with extensions to call out to other platforms such as Ruby/Rake.
Build Configuration Language: None for simple builds. XML/Nant, Ruby, and Powershell for extended scenarios
URL: http://code.google.com/p/uppercut/If you’re going to use Nant and you don’t need to do anything “unusual”, then you should be using UppercuT. This is an add-on that makes Nant so easy to use, you don’t even need to know how to use Nant. UppercuT makes good on it’s promises, too. It really is that easy to get a build up and running because you don’t need to know anything other than the basic conventions that it uses to find your solutions, tests, etc. From the project’s homepage:
It seeks to solve both maintenance concerns and ease of build to help you concentrate on what you really want to do: write code. Upgrading the build should take seconds, not hours. And that is where UppercuT will beat any other automated build system hands down. UppercuT is targeted at those who want all of the power and stability that Nant provides, but don’t want to deal with a ton of XML and build script definitions.Example: No, really… this project makes building with Nant so easy, you don’t need to configure any tasks for most things. Check out the website for more information. MSBuild: Bringing ‘One Microsoft Way’ To Your Build SystemRuntime: .NET
Build Configuration Language: XML with extensions written in .NET
URL: http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx
Read more: lostechies.com
Build Configuration Language: XML with extensions written in .NET
URL: http://nant.sourceforge.net/ Nant is the old-school guy on the .NET block, having grown up over on Java road. This is the original .NET build tool that so many others wanted to be or wanted to be better than. If you’ve used any build tools for more than a few years in .NET, you’ve probably used Nant at least once. There are a lot of extensions and add-ons to Nant, including a user contributions project, several visual tools designed to abstract away the xml, some conventions based add-ons that make nant easier, etc. If you need to do it in your build process, chances are there is a plugin or a blog post that tells you how to do it with Nant. Nant was originally a copy of the Java Ant build tool but quickly took its own directions in implementation becoming the defacto build tool in .NET for several years. With it’s heavy reliance on xml and its roots tracing back to java, most “enterprise” developers chose Nant because of it’s familiarity from the Java world. Example: Build a solution 1: <target name="compile">
2: <echo message="Build my solution!" />
3: <msbuild project="src/mysolution.sln">
4: <arg value="/property:Configuration=release" />
5: <arg value="/t:Rebuild" />
6: </msbuild>
7: </target>
UppercuT: You Won’t Know What Hit YouRuntime: .NET (Nant) with extensions to call out to other platforms such as Ruby/Rake.
Build Configuration Language: None for simple builds. XML/Nant, Ruby, and Powershell for extended scenarios
URL: http://code.google.com/p/uppercut/If you’re going to use Nant and you don’t need to do anything “unusual”, then you should be using UppercuT. This is an add-on that makes Nant so easy to use, you don’t even need to know how to use Nant. UppercuT makes good on it’s promises, too. It really is that easy to get a build up and running because you don’t need to know anything other than the basic conventions that it uses to find your solutions, tests, etc. From the project’s homepage:
It seeks to solve both maintenance concerns and ease of build to help you concentrate on what you really want to do: write code. Upgrading the build should take seconds, not hours. And that is where UppercuT will beat any other automated build system hands down. UppercuT is targeted at those who want all of the power and stability that Nant provides, but don’t want to deal with a ton of XML and build script definitions.Example: No, really… this project makes building with Nant so easy, you don’t need to configure any tasks for most things. Check out the website for more information. MSBuild: Bringing ‘One Microsoft Way’ To Your Build SystemRuntime: .NET
Build Configuration Language: XML with extensions written in .NET
URL: http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx
Read more: lostechies.com
How to get info from client certificates issued by a CA (C#)
Posted by
jasper22
at
11:37
|
Hi all,The following C# sample shows how to use Certadm.dll and CryptoAPI to get the name of the template and the enhanced usages of client certificates in a CA: <SAMPLE file="Form1.cs">
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Runtime.InteropServices;
using System.DirectoryServices;
using CERTADMINLib;namespace CertAdminTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
// Variables
string strServerName = "MyServer";
DirectoryEntry rootEntry = null;
DirectoryEntry templatesEntry = null; try
{
// Get AD entry that we will use to translate a certificate template OID to its correspondent name
rootEntry = new DirectoryEntry("LDAP://" + strServerName + "/rootDSE");
templatesEntry = new DirectoryEntry("LDAP://" + strServerName + "/cn=certificate templates,cn=public key services,cn=services,cn=configuration," + (string)rootEntry.Properties["defaultNamingContext"][0]); // Get Certificate Services Database info
ViewCertificateServicesDatabase(strServerName, strServerName, templatesEntry);
}
catch (Exception ex)
{
// Errors?
MessageBox.Show(ex.Message);
}
finally
{
// Clean up
if (rootEntry != null)
{
rootEntry.Dispose();
}
if (templatesEntry != null)
{
templatesEntry.Dispose();
}
}
} private void ViewCertificateServicesDatabase(string strServer, string strCAName, DirectoryEntry templatesEntry)
{
// Variables
CERTADMINLib.CCertView certView = null;
CERTADMINLib.IEnumCERTVIEWROW certViewRow = null;
CERTADMINLib.IEnumCERTVIEWCOLUMN certViewColumn = null;
CERTADMINLib.IEnumCERTVIEWEXTENSION certViewExt = null;
int iColumnCount = 0;
string strBase64Value = "";
string strValue = "";
string strOID = "";
int iStartIndex = 0;
string strDisplayName = "";
object objValue = null;
string strOutput = ""; // Connecting to the Certificate Authority
certView = new CERTADMINLib.CCertViewClass();
certView.OpenConnection(strServer + "\\" + strCAName); // Get a column count and place columns into the view
iColumnCount = certView.GetColumnCount(0);
certView.SetResultColumnCount(iColumnCount); // Place each column in the view.
for (int x = 0; x < iColumnCount; x++)
{
certView.SetResultColumn(x);
}Read more: Decrypt my World
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Runtime.InteropServices;
using System.DirectoryServices;
using CERTADMINLib;namespace CertAdminTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
// Variables
string strServerName = "MyServer";
DirectoryEntry rootEntry = null;
DirectoryEntry templatesEntry = null; try
{
// Get AD entry that we will use to translate a certificate template OID to its correspondent name
rootEntry = new DirectoryEntry("LDAP://" + strServerName + "/rootDSE");
templatesEntry = new DirectoryEntry("LDAP://" + strServerName + "/cn=certificate templates,cn=public key services,cn=services,cn=configuration," + (string)rootEntry.Properties["defaultNamingContext"][0]); // Get Certificate Services Database info
ViewCertificateServicesDatabase(strServerName, strServerName, templatesEntry);
}
catch (Exception ex)
{
// Errors?
MessageBox.Show(ex.Message);
}
finally
{
// Clean up
if (rootEntry != null)
{
rootEntry.Dispose();
}
if (templatesEntry != null)
{
templatesEntry.Dispose();
}
}
} private void ViewCertificateServicesDatabase(string strServer, string strCAName, DirectoryEntry templatesEntry)
{
// Variables
CERTADMINLib.CCertView certView = null;
CERTADMINLib.IEnumCERTVIEWROW certViewRow = null;
CERTADMINLib.IEnumCERTVIEWCOLUMN certViewColumn = null;
CERTADMINLib.IEnumCERTVIEWEXTENSION certViewExt = null;
int iColumnCount = 0;
string strBase64Value = "";
string strValue = "";
string strOID = "";
int iStartIndex = 0;
string strDisplayName = "";
object objValue = null;
string strOutput = ""; // Connecting to the Certificate Authority
certView = new CERTADMINLib.CCertViewClass();
certView.OpenConnection(strServer + "\\" + strCAName); // Get a column count and place columns into the view
iColumnCount = certView.GetColumnCount(0);
certView.SetResultColumnCount(iColumnCount); // Place each column in the view.
for (int x = 0; x < iColumnCount; x++)
{
certView.SetResultColumn(x);
}Read more: Decrypt my World
Hibernate: это должен помнить каждый
Posted by
jasper22
at
11:37
|
Долго мучался, разруливая зависимости между сущностями, хранящимися в БД (т.е. персистентными сущностями). Пришлось разобраться с каскадными операциями, в итоге родилась вот такая памятка:- cascade="none" - значение по умолчанию. Hibernate будет игнорировать ассоциации, поэтому разруливать зависимости придется самостоятельно. - cascade="save-update" говорит Hibernate'у, что разруливать зависимости необходимо при комите транзакции в которой делается save() или update() объекта. Суть разруливания заключается в том, что новые объекты, с которыми есть ассоциации у нашего, будут сохранены до него. Это позволяет обойти constraint-violations. - cascade="delete" говорит Hibernate'у, что надо разруливать зависимости при удалении объекта.- cascade="all" обозначает выполнение каскадных операций при save-update и delete. - cascade="all-delete-orphan" обозначает то же самое, что и cascade="all", но к тому же Hibernate удаляет любые связанные сущности, удаленные из ассоциации (например, из коллекции). - cascade="delete-orphan" обозначает, что Hibernate будет удалять любые сущности, которые были удалены из ассоциации.Part 2:При определении идентификатора - первичного ключа - таблицы в Hibernate можно явно указать стратегию генерации его значения. Делается это в мэпинге с помощью тега generator, у которого указывается атрибут class. Например, так: <id name="uid" column="uuid" type="string" length="32"> <generator class="ru.naumen.bpm.commons.util.PrefixUUIDGenerator"/></id>
Помимо того, что можно определить свою стратегию генерации как класс, реализующий интерфейс org.hibernate.id.IdentifierGenerator, фреймворк содержит ряд уже готовых генераторов. Рассмотрим их подробнее.increment - генерирует идентификаторы типов long, int и short, которые являются уникальными только если никакой другой процесс не добавляет данные в ту же самую таблицу. Данную стратегию нельзя использовать в кластерном окружении. identity - поддерживает identity-столбцы в DB2, MySQL, MS SQL Server, Sybase и HypersonicSQL. Возвращаемый идентификатор имеет тип long, int или short.sequence - использует последовательности в DB2, PostgreSQL, Oracle, SAP DB, McKoi или генераторы в Interbase. Возвращаемый идентификатор имеет тип long, int или short. hilo - использует hi/lo алгоритм для рационального генерирования идентификаторов типа long, int или short уникальных для таблицы или колонки (по умолчанию - hibernate_unique_key и next_hi, соответственно). Hi/lo алгоритм генерирует идентификаторы, которые уникальны только для конкретной базы данных. Не стоит использовать данную стратегию для соединений, установленных с помощью JTA или с помощью определяемых пользователем соединений. seqhilo - использует hi/lo алгоритм для рационального генерирования идентификаторов типа long, int или short. В качестве источника данных используются именованные последовательности.Read more: БЛОГ СУРОВОГО ЧЕЛЯБИНСКОГО ПРОГРАММИСТА Part 1, Part 2
Помимо того, что можно определить свою стратегию генерации как класс, реализующий интерфейс org.hibernate.id.IdentifierGenerator, фреймворк содержит ряд уже готовых генераторов. Рассмотрим их подробнее.increment - генерирует идентификаторы типов long, int и short, которые являются уникальными только если никакой другой процесс не добавляет данные в ту же самую таблицу. Данную стратегию нельзя использовать в кластерном окружении. identity - поддерживает identity-столбцы в DB2, MySQL, MS SQL Server, Sybase и HypersonicSQL. Возвращаемый идентификатор имеет тип long, int или short.sequence - использует последовательности в DB2, PostgreSQL, Oracle, SAP DB, McKoi или генераторы в Interbase. Возвращаемый идентификатор имеет тип long, int или short. hilo - использует hi/lo алгоритм для рационального генерирования идентификаторов типа long, int или short уникальных для таблицы или колонки (по умолчанию - hibernate_unique_key и next_hi, соответственно). Hi/lo алгоритм генерирует идентификаторы, которые уникальны только для конкретной базы данных. Не стоит использовать данную стратегию для соединений, установленных с помощью JTA или с помощью определяемых пользователем соединений. seqhilo - использует hi/lo алгоритм для рационального генерирования идентификаторов типа long, int или short. В качестве источника данных используются именованные последовательности.Read more: БЛОГ СУРОВОГО ЧЕЛЯБИНСКОГО ПРОГРАММИСТА Part 1, Part 2
Accessing Network Drive in C#
Posted by
jasper22
at
11:34
|
Problem:One of the requirements of the product that I was doing is like this: There will be a screen in a windows based application and it consists of a combo box. The combo box should display the network drives of the computer. For those who are less literate about network drives; Network Drives are those locations that are mapped to a drive or folder in another system which can be accessed over network. Usually it is often painful to manually navigate to the network location and access the files there. So windows allow us to create network drives on our machines such that we can access the desired network location with just one single click. How to create a Network Drive?The creation of network drives is a very simple process.Open My Computer --> Select tools from the menu bar--> Select the Map Network Drive option.This opens a window which has a combo box with the existing network drives and non networking drives. Upon selecting a drive the text box below the drop down list will display the path that the network is mapped to. Once you select the drive letter from the combo box , Enter the Network path in the text box and click Finish. Now you should be able to view the network drives in the my computer screen. Solution to the Problem:If you have ever worked on .NET you would certainly know how vast the base class library of .NET is. We can do many things with it. Yet, we cannot do everything using just the .NET framework and the BCL. Windows OS( XP,VISTA,WINDOWS 7) uses a special assembly called 'mrp.dll". mpr.dll is a module containing functions that are used to handle communication between the Windows operating system and the installed network providers. This assembly basically takes care of the relation between Drive Name Versus the Network Path. So we use the same .dll to fetch us the information that we need. The assembly should be referred as an external assembly and values should be passed to it. In order to do this we use the DllImport attribute method to point to the mpr.dll. We must point the Drive letters to the external Dll this should be done with the help of MarshallAs attribute. Have a look at the folowing code.public static class Pathing
{
[DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int WNetGetConnection(
[MarshalAs(UnmanagedType.LPTStr)] string localName,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,
ref int length);
/// <summary>
/// Given a path, returns the UNC path or the original. (No exceptions
/// are raised by this function directly). For example, "P:\2008-02-29"
/// might return: "\\networkserver\Shares\Photos\2008-02-09"
/// </summary>
/// <param name="originalPath">The path to convert to a UNC Path</param>
/// <returns>A UNC path. If a network drive letter is specified, the
/// drive letter is converted to a UNC or network path. If the
/// originalPath cannot be converted, it is returned unchanged.</returns>
public static string GetUNCPath(string originalPath)
{
StringBuilder sb = new StringBuilder(512);
int size = sb.Capacity;
// look for the {LETTER}: combination ...
if (originalPath.Length > 2 && originalPath[1] == ':')
{
// don't use char.IsLetter here - as that can be misleading
// the only valid drive letters are a-z && A-Z.
char c = originalPath[0];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
{
int error = WNetGetConnection(originalPath.Substring(0, 2),
sb, ref size);
if (error == 0)
{
DirectoryInfo dir = new DirectoryInfo(originalPath);
string path = Path.GetFullPath(originalPath)
.Substring(Path.GetPathRoot(originalPath).Length);
return Path.Combine(sb.ToString().TrimEnd(), path);
}
}
}
return originalPath;
}
}
Read more: C# Corner
{
[DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int WNetGetConnection(
[MarshalAs(UnmanagedType.LPTStr)] string localName,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,
ref int length);
/// <summary>
/// Given a path, returns the UNC path or the original. (No exceptions
/// are raised by this function directly). For example, "P:\2008-02-29"
/// might return: "\\networkserver\Shares\Photos\2008-02-09"
/// </summary>
/// <param name="originalPath">The path to convert to a UNC Path</param>
/// <returns>A UNC path. If a network drive letter is specified, the
/// drive letter is converted to a UNC or network path. If the
/// originalPath cannot be converted, it is returned unchanged.</returns>
public static string GetUNCPath(string originalPath)
{
StringBuilder sb = new StringBuilder(512);
int size = sb.Capacity;
// look for the {LETTER}: combination ...
if (originalPath.Length > 2 && originalPath[1] == ':')
{
// don't use char.IsLetter here - as that can be misleading
// the only valid drive letters are a-z && A-Z.
char c = originalPath[0];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
{
int error = WNetGetConnection(originalPath.Substring(0, 2),
sb, ref size);
if (error == 0)
{
DirectoryInfo dir = new DirectoryInfo(originalPath);
string path = Path.GetFullPath(originalPath)
.Substring(Path.GetPathRoot(originalPath).Length);
return Path.Combine(sb.ToString().TrimEnd(), path);
}
}
}
return originalPath;
}
}
Read more: C# Corner
A Brief, Incomplete, and Mostly Wrong History of Programming Languages
Posted by
jasper22
at
11:05
|
1936 - Alonzo Church also invents every language that will ever be but does it better. His lambda calculus is ignored because it is insufficiently C-like. This criticism occurs in spite of the fact that C has not yet been invented. 1972 - Dennis Ritchie invents a powerful gun that shoots both forward and backward simultaneously. Not satisfied with the number of deaths and permanent maimings from that invention he invents C and Unix.1972 - Alain Colmerauer designs the logic language Prolog. His goal is to create a language with the intelligence of a two year old. He proves he has reached his goal by showing a Prolog session that says "No." to every query. 1980 - Alan Kay creates Smalltalk and invents the term "object oriented." When asked what that means he replies, "Smalltalk programs are just objects." When asked what objects are made of he replies, "objects." When asked again he says "look, it's all objects all the way down. Until you reach turtles." 1983 - Bjarne Stroustrup bolts everything he's ever heard of onto C to create C++. The resulting language is so complex that programs must be sent to the future to be compiled by the Skynet artificial intelligence. Build times suffer. Skynet's motives for performing the service remain unclear but spokespeople from the future say "there is nothing to be concerned about, baby," in an Austrian accented monotones. There is some speculation that Skynet is nothing more than a pretentious buffer overrun. 1986 - Brad Cox and Tom Love create Objective-C, announcing "this language has all the memory safety of C combined with all the blazing speed of Smalltalk." Modern historians suspect the two were dyslexic Read more: ONE DIV ZERO
13 Top Virtualization Vendors all around the World
Posted by
jasper22
at
10:58
|
Here is the list of top virtualization vendors all around the world:1. VMWare (Virtual Machine Software)Find a major data center anywhere in the world that doesn't use VMware,.VMware owns anywhere from 55-85% of the virtualization market. VMware dominates the server virtualization market. VMware also dominates the desktop-level virtualization market and perhaps even the free server virtualization market with its VMware Server product. VMware remains in the dominant spot due to its innovations, strategic partnerships and rock-solid products.
2. CitrixOpen-source alternative to VMware.3. Oracle4. MicrosoftMicrosoft Virtual Server was a dud. Virtual Server has captured a scant 7% market share.Viridian also failed to perform and comptete in the market. 5. Red HatFor the past 15 years, everyone has recognized Red Hat as an industry leader and open source champion. Hailed as the most successful open source company, Red Hat entered the world of virtualization in 2008 when it purchased Qumranet and with it, its own virtual solution: KVM and SPICE (Simple Protocol for Independent Computing Environment). Red Hat released the SPICE protocol as open source in December 2009. 6. AmazonAmazon's Elastic Compute Cloud (EC2) is the industry standard virtualization platform. Ubuntu's Cloud Server supports seamless integration with Amazon's EC2 services. EngineYard's Ruby application services leverage Amazon's cloud as well. 7. GoogleWhen you think of Google, virtualization might not make the top of the list of things that come to mind, but its Google Apps, AppEngine and extensive Business Services list demonstrates how it has embraced cloud-oriented services. Read more: Hello Tech Guys
2. CitrixOpen-source alternative to VMware.3. Oracle4. MicrosoftMicrosoft Virtual Server was a dud. Virtual Server has captured a scant 7% market share.Viridian also failed to perform and comptete in the market. 5. Red HatFor the past 15 years, everyone has recognized Red Hat as an industry leader and open source champion. Hailed as the most successful open source company, Red Hat entered the world of virtualization in 2008 when it purchased Qumranet and with it, its own virtual solution: KVM and SPICE (Simple Protocol for Independent Computing Environment). Red Hat released the SPICE protocol as open source in December 2009. 6. AmazonAmazon's Elastic Compute Cloud (EC2) is the industry standard virtualization platform. Ubuntu's Cloud Server supports seamless integration with Amazon's EC2 services. EngineYard's Ruby application services leverage Amazon's cloud as well. 7. GoogleWhen you think of Google, virtualization might not make the top of the list of things that come to mind, but its Google Apps, AppEngine and extensive Business Services list demonstrates how it has embraced cloud-oriented services. Read more: Hello Tech Guys
New Bing Screensaver
Posted by
jasper22
at
10:57
|
These days, we no longer need screensavers to prevent “burn in” of images on our computer’s screens – those types of problems are, truly, a relic of another era, thank goodness (for LCD anyway).That said, there’s no reason why you can’t use a screensaver just to brighten up your idle PC with a little beauty, art, or other images that just make you smile. (I enjoy a montage of my new baby’s pictures, for example). If you also enjoy screensavers, there’s a lovely new one appearing here on Microsoft’s “DiscoverBing.co.uk” website. The Bing screensaver includes a number of the most popular images from the Bing.com homepage – the same images you’ll find in the popular themepacks Bing’s Best and Bing's Best 2. Read more: on10
Resolve a URL from a Partial View (ASP.NET MVC)
Posted by
jasper22
at
10:56
|
Working on an ASP.NET MVC application and needed the ability to resolve a URL from a partial view. For example, I have an image I want to display, but I need to resolve the virtual path (say, ~/Content/Images/New.png) into a relative path that the browser can use, such as ../../Content/Images/New.png or /MyAppName/Content/Images/New.png. A standard view derives from the System.Web.UI.Page class, meaning you have access to the ResolveUrl and ResolveClientUrl methods. Consequently, you can write markup/code like the following:<img src='=<%=Page.ResolveClientUrl("~/Content/Images/New.png")%>' /> The problem is that the above code does not work as expected in a partial view. What's a little confusing is that while the above code compiles and the page, when visited through a browser, renders, the call to Page.ResolveClientUrl returns precisely what you pass in, ~/Content/Images/New.png, in this instance. The browser doesn't know what to do with ~, it presumes it's part of the URL, so it sends the request to the server for the image with the ~ in the URL, which results in a broken image. I did a bit of searching online and found this handy tip from Stephen Walther - Using ResolveUrl in an HTML Helper. In a nutshell, Stephen shows how to create an extension method for the HtmlHelper class that uses the UrlHelper class to resolve a URL. Specifically, Stephen shows how to add an Image extension method to HtmlHelper. I incorporated Stephen's code into my codebase and also created a more generic extension method, which I named ResolveUrl. Read more: Scott on Writing
New from Microsoft: Surreal Terrority Windows 7 Theme
Posted by
jasper22
at
10:54
|
I love that Microsoft keeps updating their collection of themes for Windows 7 because - I have to admit - I quickly grow bored with my desktop background and color schemes. I like to switch it up pretty often and the themes feature in Windows 7 lets me do that easily. With themes, my wallpaper isn’t static – it rotates through a series of images on an interval I specify. The latest theme to grace my desktop is the gorgeous, brightly-hued creation from artist Chuck Anderson called “Surreal Territory.” The theme includes a few different images of landscapes and sky but with a twist. Instead of the natural colors found in nature, the sky is colorized with rainbow-colored tones. Just lovely. Read more: on10
No More Boxes! Exploring the PathListBox (Silverlight TV #25)
Posted by
jasper22
at
10:53
|
In this video, Adam Kinney explains what the PathListBox is and why it is so compelling. Then, he demonstrates several ways of using it in creative examples. The PathListBox is one of the newest features available in Expression Blend and Silverlight 4. It redefines how users look at lists of data as it breaks the mold of a list "box" and opens the possibilities to use any shape or path. Don't miss this episode and be sure to download Adam's sample code. Relevant links:John's Blog and on Twitter (@john_papa)
Adam's Blog and on Twitter (@adkinn)
Get Expression Blend 4 RC trial
Source code for Adam's PathListBox demos
Adam's blog post on PathListBox
Follow us on Twitter @SilverlightTV or on the web at http://silverlight.tv/Read more: JohnPapa.net
Video: Channel9
Adam's Blog and on Twitter (@adkinn)
Get Expression Blend 4 RC trial
Source code for Adam's PathListBox demos
Adam's blog post on PathListBox
Follow us on Twitter @SilverlightTV or on the web at http://silverlight.tv/Read more: JohnPapa.net
Video: Channel9
Three nice opensource games for Linux
Posted by
jasper22
at
10:51
|
My today selection for Linux gamers are three nice opensource games, the games are Go Ollie! : At first sight Go Ollie! looks like a game for kids, but once you play it you realize it can be fun for anyone, no matter what age.
Bos Wars : A futuristic real time strategy game (RTS)
Scorched 3D : A simple turn-based artillery game and also a real-time strategy game in which players can counter each others' weapons with other creative accessories, shields and tactics.
Go Ollie !At first sight Go Ollie! looks like a game for kids, but once you play it you realize it can be fun for anyone, no matter what age.Go Ollie! is an original platform game that stands out for several reasons. First, its main character is a worm, a tiny creature that is not usually regarded as an example of cuteness. Second, the worm is controlled with the mouse instead of cursor keys. And finally, the game scrolls automatically to one side, just like one of those old shoot'em ups. In Go Ollie! your mission consists on collecting all the coins, fruits and whatever other valuable objects you find on your way. At the same time you'll have to avoid different kinds of enemies. Go Ollie! features two gaming modes: a Story mode that enables you to play over 60 levels with various objectives and an Action mode with unlimited replayable levels and a high score top list. For Ubuntu Users you can install the game from Playdeb ( Be sure first to add the repositories of playdeb)Read more: Unixmen
Bos Wars : A futuristic real time strategy game (RTS)
Scorched 3D : A simple turn-based artillery game and also a real-time strategy game in which players can counter each others' weapons with other creative accessories, shields and tactics.
Go Ollie !At first sight Go Ollie! looks like a game for kids, but once you play it you realize it can be fun for anyone, no matter what age.Go Ollie! is an original platform game that stands out for several reasons. First, its main character is a worm, a tiny creature that is not usually regarded as an example of cuteness. Second, the worm is controlled with the mouse instead of cursor keys. And finally, the game scrolls automatically to one side, just like one of those old shoot'em ups. In Go Ollie! your mission consists on collecting all the coins, fruits and whatever other valuable objects you find on your way. At the same time you'll have to avoid different kinds of enemies. Go Ollie! features two gaming modes: a Story mode that enables you to play over 60 levels with various objectives and an Action mode with unlimited replayable levels and a high score top list. For Ubuntu Users you can install the game from Playdeb ( Be sure first to add the repositories of playdeb)Read more: Unixmen
8085 Microprocessor simulator
Posted by
jasper22
at
10:50
|
A cool way to learn and write 8085 assembly language programs. Gone are the days when you punched in the assembly language in hex format and hoped nothing went wrong.The salient features include.
Write your programs using the syntax highlighting text editor which also gives contextual help in the status bar.
A built in 2 pass assembler and a full source level debugger to simulate/debug your 8085 programs.
View the state of the memory / register / flags.
Modify any memory location / register / instructions.
Set breakpoints.
Modify instructions at runtime with syntax checking.This software is completely free and comes with the full source code which can be compiled using VS2005. Read more: Codeplex
Write your programs using the syntax highlighting text editor which also gives contextual help in the status bar.
A built in 2 pass assembler and a full source level debugger to simulate/debug your 8085 programs.
View the state of the memory / register / flags.
Modify any memory location / register / instructions.
Set breakpoints.
Modify instructions at runtime with syntax checking.This software is completely free and comes with the full source code which can be compiled using VS2005. Read more: Codeplex
May 2010 Security Release ISO Image
Posted by
jasper22
at
09:55
|
This DVD5 ISO image file contains the security updates for Windows released on Windows Update on May 11th, 2010. The image does not contain security updates for other Microsoft products. This DVD5 ISO image is intended for administrators that need to download multiple individual language versions of each security update and that do not use an automated solution such as Windows Server Update Services (WSUS). You can use this ISO image to download multiple updates in all languages at the same time. Important: Be sure to check the individual security bulletins at http://www.microsoft.com/technet/security prior to deployment of these updates to ensure that the files have not been updated at a later date. This DVD5 image contains the following updates: KB978542 / (MS10-030)
Windows 2000 - 24 languages
Windows Server 2003 - 18 languages
Windows Server 2003 x64 Edition - 11 languages
Windows Server 2003 for Itanium-based Systems - 4 languages
Windows XP - 24 languages
Windows XP x64 Edition - 2 languages
Windows Vista - 36 languages
Windows Vista for x64-based Systems - 36 languages
Windows Server 2008 - 19 languages
Windows Server 2008 x64 Edition - 19 languages
Windows Server 2008 for Itanium-based Systems - 4 languages
Windows 7 - 36 languages
Windows 7 for x64-based Systems - 36 languages
Windows Server 2008 R2 x64 Edition - 19 languages
Windows Server 2008 R2 for Itanium-based Systems - 4 languages Read more: MS Download
Windows Server 2003 - 18 languages
Windows Server 2003 x64 Edition - 11 languages
Windows Server 2003 for Itanium-based Systems - 4 languages
Windows XP - 24 languages
Windows XP x64 Edition - 2 languages
Windows Vista - 36 languages
Windows Vista for x64-based Systems - 36 languages
Windows Server 2008 - 19 languages
Windows Server 2008 x64 Edition - 19 languages
Windows Server 2008 for Itanium-based Systems - 4 languages
Windows 7 - 36 languages
Windows 7 for x64-based Systems - 36 languages
Windows Server 2008 R2 x64 Edition - 19 languages
Windows Server 2008 R2 for Itanium-based Systems - 4 languages Read more: MS Download
GETTING STARTED BUILDING A WCF WEB SERVICE
Posted by
jasper22
at
09:48
|
This post is one in a series of upcoming MSDN articles. It shows how to create a very simple web service using Windows Communications Founcation (WCF). There is one special characteristic of the web service that I present in this article, which is that while it is very simple, it can be consumed as an External Content Type (ECT) from Business Connectivity Services (BCS). In addition, the procedure presented in this post shows how to host this web service using Internet Information Services (IIS). The subject of the series is creating a claims-aware web service and consuming it from SharePoint BCS. In the short time that I’ve worked with claims-based authentication, what I experience is that while there are not very many steps to get it working, if you get anything wrong, then it just doesn’t work, and it takes some effort to figure out the problem. My approach in these articles is to supply some procedures with small steps, with instructions all along the way to validate that what you have done so far works properly. So the first step is to create a WCF web service, host it using IIS, and validate that it is working. In the second article, I’m going to add some Windows Identity Framework (WIF) capabilities, so that the web service can report on the identity of the user of the web service.In the third article, I’ll walk through consuming the web service from BCS. In the fourth article, I’ll show how to move the web service to a different machine, make it claims-aware, and then again, consume it from BCS. This solves the ‘double hop’ problem.As usual, after these blog posts are published as MSDN articles, I’ll update posts with a links to the MSDN articles. This web service contains only two methods: a ‘finder’ to retrieve a collection of items, and a ‘specific finder’ to retrieve a single item. The ‘database’ behind the collection is just an initialized list. The ‘schema’ of this little ‘database’ is very simple. It is a single flat table consisting of two fields – an integer CustomerID, and a string CustomerName. CustomerID is a unique ID. Read more: Eric White's Blog
ClosedXML - The easy way to OpenXML
Posted by
jasper22
at
09:47
|
ClosedXML makes it easier for developers to create OpenXML files for Excel 2007. It provides a nice object oriented way to manipulate the files (similar to VBA) without dealing with the hassles of XML Documents. It's developed in C# but can be used by any other .NET language. What can you do with this?ClosedXML allows you to create Excel 2007/2010 files without the Excel application. If you ever used the Microsoft Open XML Format SDK you know just how much code you have to write to get the same results as the following 4 lines of code. var workbook = new XLWorkbook("Sample.xlsx");
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
workbook.Save(); Development StatusThe current build has the following simple capabilities:
Can create new workbooks
Add worksheets
Access cells using R1C1 and A1 notation.
Add text, dates, booleans, and numbers to cells
Select ranges (not named ranges though)
Traverse a range's columns and rowsRead more: Codeplex
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
workbook.Save(); Development StatusThe current build has the following simple capabilities:
Can create new workbooks
Add worksheets
Access cells using R1C1 and A1 notation.
Add text, dates, booleans, and numbers to cells
Select ranges (not named ranges though)
Traverse a range's columns and rowsRead more: Codeplex
Integrating Twitter Into An ASP.NET Website Using OAuth
Posted by
jasper22
at
09:46
|
Earlier this year I wrote an article about Twitterizer, an open-source .NET library that can be used to integrate your application with Twitter. Using Twitterizer you can allow your visitors to post tweets, view their timeline, and much more, all without leaving your website. The original article, Integrating Twitter Into An ASP.NET Website, showed how to post tweets and view a timeline to a particular Twitter account using Twitterizer 1.0. To post a tweet to a specific account, Twitterizer 1.0 uses basic authentication. Basic authentication is a very simple authentication scheme. For an application to post a tweet to JohnDoe's Twitter account, it would submit JohnDoe's username and password (along with the tweet text) to Twitter's servers. Basic authentication, while easy to implement, is not an ideal authentication scheme as it requires that the integrating application know the username(s) and password(s) of the accounts that it is connected to. Consequently, a user must share her password in order to connect her Twitter account with the application. Such password sharing is not only insecure, but it can also cause difficulties down the line if the user changes her password or decides that she no longer wants to connect her account to certain applications (but wants to remain connected to others). To remedy these issues, Twitter introduced support for OAuth, which is a simple, secure protocol for granting API access. In a nutshell, OAuth allows a user to connect an application to their Twitter account without having to share their password. Instead, the user is sent to Twitter's website where they confirm whether they want to connect to the application. Upon confirmation, Twitter generates an token that is then sent back to the application. The application then submits this token when integrating with the user's account. The token serves as proof that the user has allowed this application access to their account. (Twitter users can view what application's they're connected to and may revoke these tokens on an application-by-application basis.) In late 2009, Twitter announced that it was ending its support for basic authentication in June 2010. As a result, the code examined in Integrating Twitter Into An ASP.NET Website, which uses basic authentication, will no longer work once the cut off date is reached. The good news is that the Twitterizer version 2.0 supports OAuth. This article examines how to use Twitterizer 2.0 and OAuth from a website. Specifically, we'll see how to retrieve and display a user's latest tweets and how to post a tweet from an ASP.NET page. Read on to learn more! Read more: 4 Guys from Rolla
Subscribe to:
Posts (Atom)