Joseph Michael Pesch
VP Programming

C# Map Network Drive

by 19. January 2011 09:09
/* == Calling code ================================ */
Utilities.Network.DriveMapping.DelDrive("i:", 0, true);
Utilities.Network.DriveMapping.MapDrive(@"\\server\folder""i:"@"domain\user""password");
/* == Class ======================================= */
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;


namespace Utilities.Network
{
  public static class DriveMapping
  {
    public enum ResourceScope
    {
      RESOURCE_CONNECTED = 1,
      RESOURCE_GLOBALNET,
      RESOURCE_REMEMBERED,
      RESOURCE_RECENT,
      RESOURCE_CONTEXT
    }
 
    public enum ResourceType
    {
      RESOURCETYPE_ANY,
      RESOURCETYPE_DISK,
      RESOURCETYPE_PRINT,
      RESOURCETYPE_RESERVED
    }
 
    public enum ResourceUsage
    {
      RESOURCEUSAGE_CONNECTABLE = 0x00000001,
      RESOURCEUSAGE_CONTAINER = 0x00000002,
      RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004,
      RESOURCEUSAGE_SIBLING = 0x00000008,
      RESOURCEUSAGE_ATTACHED = 0x00000010,
      RESOURCEUSAGE_ALL = (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED),
    }
 
    public enum ResourceDisplayType
    {
      RESOURCEDISPLAYTYPE_GENERIC,
      RESOURCEDISPLAYTYPE_DOMAIN,
      RESOURCEDISPLAYTYPE_SERVER,
      RESOURCEDISPLAYTYPE_SHARE,
      RESOURCEDISPLAYTYPE_FILE,
      RESOURCEDISPLAYTYPE_GROUP,
      RESOURCEDISPLAYTYPE_NETWORK,
      RESOURCEDISPLAYTYPE_ROOT,
      RESOURCEDISPLAYTYPE_SHAREADMIN,
      RESOURCEDISPLAYTYPE_DIRECTORY,
      RESOURCEDISPLAYTYPE_TREE,
      RESOURCEDISPLAYTYPE_NDSCONTAINER
    }
 
    [StructLayout(LayoutKind.Sequential)]
    private class NETRESOURCE
    {
      public ResourceScope dwScope = 0;
      public ResourceType dwType = 0;
      public ResourceDisplayType dwDisplayType = 0;
      public ResourceUsage dwUsage = 0;
      public string lpLocalName = null;
      public string lpRemoteName = null;
      public string lpComment = null;
      public string lpProvider = null;
    }
 
    [DllImport("mpr.dll")]
    private static extern int WNetAddConnection2(NETRESOURCE lpNetResource, string lpPassword, string lpUsername, int dwFlags);
 
    [DllImport("mpr.dll")]
    private static extern int WNetCancelConnection2(string name, int flags, bool force);
 
    public static bool DelDrive(string name, int flags, bool force)
    {
      int result = WNetCancelConnection2(name, flags, force);
      if (!result.Equals(0))
      {
        throw new Win32Exception((int)result);
      }
      return true;
    }
 
    public static bool MapDrive(string unc, string drive, string user, string password)
    {
      /*
       NOTE: If you receive the following error message try connecting by IP address rather then server name:
             Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. 
             Disconnect all previous connections to the server or shared resource and try again
      */
      NETRESOURCE myNetResource = new NETRESOURCE();
      myNetResource.lpLocalName = drive;
      myNetResource.lpRemoteName = unc;
      myNetResource.lpProvider = null;
      int result = WNetAddConnection2(myNetResource, password, user, 0);
      if (!result.Equals(0))
      {
        throw new Win32Exception((int)result);
      }
      return true;
    }
  }
}

 

Tags:

C#

Asp.Net Url Rewriting Alternative .Net Framework 4.0 RouteTable

by 13. January 2011 11:50

/* Global.asax.cs */

using System;
using System.Collections;
using System.Configuration;
using System.Linq;
using System.Web.Routing;
 
namespace JMP.UrlReWrite
{
  public class Global_ASAX : System.Web.HttpApplication
  {
    protected void Application_Start()
    {
      RegisterRoutes(RouteTable.Routes);
    }
    public static void RegisterRoutes(RouteCollection routes)
    {
      Hashtable tbl = (Hashtable)ConfigurationManager.GetSection("RouteTable");
      foreach (DictionaryEntry de in tbl)
        routes.MapPageRoute((de.Key.ToString().Split('/').Count() == 1) 
          ? de.Key.ToString() : Guid.NewGuid().ToString()
          , de.Key.ToString(), de.Value.ToString());
    }
  }
}

/* Default.aspx.cs */

using System;

namespace JMP.UrlRewrite
{
  public partial class _Default : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if (Page.RouteData.Values.ContainsKey("module"))
        switch (Page.RouteData.Values["module"].ToString())
        {
          case "aboutus": Response.RedirectToRoute("about"); break;
          defaultreturn;
        }
    }
  }
}

/* web.config */

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <configSections>
    <section name="RouteTable" type="System.Configuration.DictionarySectionHandler" />
  </configSections>
  <RouteTable>
    <add key="home" value="~/default.aspx" />
    <add key="home/{module}" value="~/default.aspx" />
    <add key="about" value="~/aboutus.aspx" />
    <!-- aboutus is being mapped in default.aspx.cs just to illustrate reading the parameters -->
    <!-- test url: ~/home/aboutus -->
    <add key="contact" value="~/contactus.aspx" />
    <add key="contactus" value="~/contactus.aspx" />
  </RouteTable>
  <system.webServer>
    <handlers>
      <add
        name="UrlRoutingHandler"
        preCondition="integratedMode"
        verb="*" path="UrlRouting.axd"
        type="System.Web.HttpForbiddenHandler, System.Web,  
          Version=2.0.0.0, Culture=neutral,  
          PublicKeyToken=b03f5f7f11d50a3a"/>
    </handlers>
    <validation validateIntegratedModeConfiguration="false"></validation>
    <modules runAllManagedModulesForAllRequests="true">
     <remove name="UrlRoutingModule"/>
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </modules>
  </system.webServer>
  <connectionStrings>
  </connectionStrings>
  <system.web>
    <customErrors mode="Off" />
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
      </assemblies>
      <buildProviders>
      </buildProviders>
    </compilation>
    <httpRuntime maxRequestLength="2000000" />
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
      <controls>
      </controls>
      <namespaces>
        <add namespace="System.Collections.Generic" />
        <add namespace="System.IO" />
      </namespaces>
    </pages>
  </system.web>
  <appSettings>
  </appSettings>
  <system.net>
  </system.net>
</configuration>

 

Tags:

ASP.Net

SQL Read XML to Generate Table Inserts

by 12. January 2011 10:41

set nocount on

 

-- Sample XML

declare @xmlData XML, @xpath varchar(250)

set @xmlData =

'

<xml>

  <schema>

    <table id="Wholesale.EmailSignUp" schema="Wholesale" name="EmailSignUp">

      <col id="EmailAddress" type="varchar" length="150" nullable="false" quote="''" />

      <col id="CompanyName" type="varchar" length="150" nullable="true" quote="''" />

      <col id="FirstName" type="varchar" length="25" nullable="true" quote="''" />

      <col id="LastName" type="varchar" length="25" nullable="true" quote="''" />

      <col id="PositionAtCompany" type="varchar" length="100" nullable="true" quote="''" />

      <col id="EntryDate" type="datetime" length="25" nullable="false" quote="''" />

      <col id="UpdateDate" type="datetime" length="25" nullable="false" quote="''" />

    </table>

    <table id="dbo.ProductsInfo" schema="dbo" name="ProductsInfo">

      <col id="ProductInfoId" type="uniquidentifier" length="" nullable="false" quote="''" />

      <col id="FieldName" type="varchar" length="50" nullable="true" quote="''" />

      <col id="DisplayText" type="varchar" length="100" nullable="true" quote="''" />

      <col id="Value" type="int" length="" nullable="true" quote="" />

    </table>

  </schema>

  <data>

    <table id="Wholesale.EmailSignUp">

      <row id="1">

        <col id="EmailAddress" value="joe.pesch@impaccompanies.com" />

        <col id="CompanyName" value="Impac" />

        <col id="FirstName" value="Joe" />

        <col id="LastName" value="Pesch" />

        <col id="PositionAtCompany" value="VP Software Development" />

        <col id="EntryDate" value="1/1/2011 7:00AM" />

        <col id="UpdateDate" value="1/1/2011 7:00AM" />

      </row>   

      <row id="2">

        <col id="EmailAddress" value="jpesch@impaccompanies.com" />

        <col id="CompanyName" value="Impac" />

        <col id="FirstName" value="Joe" />

        <col id="LastName" value="Pesch" />

        <col id="PositionAtCompany" value="VP Software Development" />

        <col id="EntryDate" value="1/1/2011 8:00AM" />

        <col id="UpdateDate" value="1/1/2011 8:00AM" />

      </row>   

    </table>

    <table id="dbo.ProductsInfo" schema="dbo" name="ProductsInfo">

      <row id="1">

        <col id="ProductInfoId" value="EEC326F3-C445-4B44-8C42-4E4FF84FDE1E" />

        <col id="FieldName" value="TESTING" />

        <col id="DisplayText" value="This is a test" />

        <col id="Value" value="100" />

      </row>   

      <row id="2">

        <col id="ProductInfoId" value="3F5F1FB8-5023-4FCD-ACF4-2B7CD25E6043" />

        <col id="FieldName" value="TESTING_ANOTHER" />

        <col id="DisplayText" value="This is another test" />

        <col id="Value" value="200" />

      </row>   

    </table>

  </data>

</xml>

'

 

-- Temp table for inserts

create table #inserts(id varchar(100), data text)

declare @handle int, @datalen int, @txtptr binary(16)

 

-- Variables for processing

declare @tbl varchar(150), @col varchar(50), @comma varchar(1), @value varchar(max)

 

-- Get handle to XML document

exec sp_xml_PrepareDocument@handle output, @xmlData

 

-- Iterate each table in the XML

declare cur cursor for select id from openxml(@handle, '/xml/schema/table', 1) with (id varchar(50))

open cur

while 'For each table in XML' <> '' begin

  fetch next from cur into @tbl

  if @@fetch_status <> 0 break

  if 'Generate the template record' <> '' begin

    set @xpath = '/xml/data/table[@id=''' + @tbl + ''']/row'

    insert into #inserts values(@tbl + '.0', 'insert into ' + @tbl + '(')

    set @comma = ''

    set @xpath = '/xml/schema/table[@id=''' + @tbl + ''']/col'

    declare @id varchar(50), @type varchar(50), @length varchar(50), @nullable varchar(50), @quote varchar(50)

    declare curX cursor for

      select [id], [type], [length], [nullable], [quote]

      from openxml(@handle, @xpath, 1)

      with ([id] varchar(50), [type] varchar(50), [length] varchar(50), [nullable] varchar(50), [quote] varchar(50))

    open curX

    while 'Process each column' <> '' begin

      fetch next from curX into @id, @type, @length, @nullable, @quote

      if @@fetch_status <> 0 break

      set @col = @comma + @id

      select @datalen = datalength(data) from #inserts where id = @tbl + '.0'

      select @txtptr = textptr(data) from #inserts where id = @tbl + '.0'

      updatetext #inserts.data @txtptr @datalen 0 @col

      set @comma = ', '

    end

    select @datalen = datalength(data) from #inserts where id = @tbl + '.0'

    select @txtptr = textptr(data) from #inserts where id = @tbl + '.0'

    updatetext #inserts.data @txtptr @datalen 0 ') values('

    close curX

    deallocate curX

  end

  if 'Generate the values using template' <> '' begin

    set @comma = ''

    set @xpath = '/xml/data/table[@id=''' + @tbl + ''']/row'

    declare curX cursor for

      select [id] from openxml(@handle, @xpath, 1) with ([id] varchar(50))

    open curX

    while 'Process each row' <> '' begin

      fetch next from curX into @id

      if @@fetch_status <> 0 break

      insert #inserts select @tbl + '.' + @id, data from #inserts where id = @tbl + '.0'

      set @xpath = '/xml/data/table[@id=''' + @tbl + ''']/row[@id=' + @id + ']/col'

      declare curY cursor for select [id], [value] from openxml(@handle, @xpath, 1) with ([id] varchar(50), [value] varchar(max))

      open curY

      set @comma = ''

      while 'Process each column' <> '' begin

        fetch next from curY into @col, @value

        if @@fetch_status <> 0 break

        set @xpath = '/xml/schema/table[@id=''' + @tbl + ''']/col[@id=''' + @col + ''']'

        select @quote = [quote]

        from openxml(@handle, @xpath, 1) with ([quote] varchar(10))

        set @value = @comma + @quote + replace(@value, '''', '''''') + @quote

        select @datalen = datalength(data) from #inserts where id = @tbl + '.' + @id

        select @txtptr = textptr(data) from #inserts where id = @tbl + '.' + @id

        updatetext #inserts.data @txtptr @datalen 0 @value

        set @comma = ','

      end

      close curY

      deallocate curY

      select @datalen = datalength(data) from #inserts where id = @tbl + '.' + @id

      select @txtptr = textptr(data) from #inserts where id = @tbl + '.' + @id

      updatetext #inserts.data @txtptr @datalen 0 ')'

    end

    close curX

    deallocate curX

    delete from #inserts where id = @tbl + '.0'

  end

end

close cur

deallocate cur

 

select * from #inserts

drop table #inserts

 

Tags:

Append to Text Column in SQL Server

by 12. January 2011 08:49

declare @datalen int

create table #inserts(id int, data text)

insert #inserts values(1, 'testing')

select @datalen = datalength(data) from #inserts where id = 1

declare @txtptr binary(16);

select @txtptr = textptr(data) from #inserts where id = 1

updatetext #inserts.data @txtptr @datalen 0 '... more data ...'

select * from #inserts

drop table #inserts

 

Tags:

Asp.Net Url Manipulation

by 10. January 2011 16:53

public static string ToAbsoluteUri(string sPath)
{
  return HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute(sPath);
}
 
[Obsolete("Consider using ToAbsoluteUri(sPath) instead.")]
public static string RootUrl
{
  get
  {
return HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
  }
}

Tags:

Windows Installation Cleaner - Remove Broker Applications

by 9. January 2011 19:35

Tags:

Model View View Model (MVVM) Silverlight Sample

by 9. January 2011 10:21

Tags:

ASP.Net | Silverlight

Simple Web Serivce Call (without Registering Service) Using HttpWebRequest Method

by 22. December 2010 08:13

SimpleWebService.ASMX:

<%@ WebService Language="C#" Class="SimpleWebService" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

[WebService(Namespace = "http://JMP-Sample.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class SimpleWebService  : System.Web.Services.WebService {
  [WebMethod]
  public string WsTestMethod(long TestId, string TestData)
  {
    return string.Join(" ""You sent TestId:", TestId.ToString(), "; TestData:", TestData);
  }
}

 

SimpleWebService.ASPX:

 

<%@ Page Language="C#" %>

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Text" %>
<script runat="server">
  protected string RootUrl
  {
    get
    {
      string query = (Request.QueryString == null) ? "" : "?" + Request.QueryString.ToString();
      return Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, string.Empty).Replace(query, string.Empty);
    }
  }
  protected void SubmitButton_Click(object sender, EventArgs e)
  {
    string soap =
    @"<?xml version=""1.0"" encoding=""utf-8""?>
      <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
        xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" 
        xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
      <soap:Body>
        <WsTestMethod xmlns=""http://JMP-Sample.org/"">
          <TestId>" + this.TestId.Text + @"</TestId>
          <TestData>" + this.TestData.Text + @"</TestData>
        </WsTestMethod>
      </soap:Body>
    </soap:Envelope>";

    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(
      string.Join("", RootUrl, ResolveUrl("~/SimpleWebService.asmx")));
    req.Headers.Add("SOAPAction""\"http://JMP-Sample.org/WsTestMethod\"");
    req.ContentType = "text/xml;charset=\"utf-8\"";
    req.Accept = "text/xml";
    req.Method = "POST";

    Stream str = req.GetRequestStream();
    using (StreamWriter wri = new StreamWriter(str)) wri.Write(soap);

    WebResponse res = req.GetResponse();
    str = res.GetResponseStream();
    this.WsResults.Text = StreamToString(str);

  }

  private string StreamToString(Stream str)
  {
    using (BinaryReader rdr = new BinaryReader(str))
    {
      using (MemoryStream mem = new MemoryStream())
      {
        byte[] buf = new byte[256];
        int bt;
        int bts = 0;
        while ((bt = rdr.Read(buf, 0, 256)) > 0)
        {
          mem.Write(buf, 0, bt);
          bts += bt;
        }
        mem.Position = 0;
        byte[] bytes = new byte[bts];
        mem.Read(bytes, 0, bytes.Length);
        return Encoding.ASCII.GetString(bytes);
      }
    }
  }
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:TextBox ID="TestId" Text="12345" runat="server"></asp:TextBox>
    <asp:TextBox ID="TestData" Text="Simple Web Service" runat="server"></asp:TextBox>
    <asp:Button ID="SubmitButton" OnClick="SubmitButton_Click" Text="Run Web Service"
      runat="server" />
    <asp:Literal ID="WsResults" runat="server"></asp:Literal>
  </div>
  </form>
</body>
</html>

 

Tags:

ASP.Net | C# | Web Service

Invalid postback or callback argument... Client side dynamic drop-down list values cannot be posted back to server

by 21. December 2010 11:39

If you attempt to change drop-down list options dynamically on the client side you may have issues with postback as the drop-down options will not match what the server originally sent to the client.  One way to overcome this is to have a server control with all the possible values (that is hidden on the UI) and a visible client side only drop-down list that is dynamically changed.  As the client side drop-down values are changed keep the server side control synchronized and then use the server side control value on post-back.  Simple sample below:

<%@ Page Language="C#" %>
 <script runat="server">
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!Page.IsPostBack)
    {
      this.ServerSelect.DataSource = new string[] { "one""two""three""four""five" };
      this.ServerSelect.DataBind();
    }
  }
  protected void SubmitButton_Click(object sender, EventArgs e)
  {
    this.ResultLabel.Text = string.Join(" ""You selected value:"this.ServerSelect.SelectedValue.ToString());
  }
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function () {
      $.each(["one""two""three""four""five"], function (index, value) {
        $('select#LocalSelect').append($('<option></option>').val(value).html(value));
      });

      $('select#LocalSelect').change(function () {
        $('select#<%=ServerSelect.ClientID%>').val($('select#LocalSelect').val());
      });
    });
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:DropDownList ID="ServerSelect" runat="server" Style="display: none;" />
    <select id="LocalSelect">
    </select>
    <asp:Button ID="SubmitButton" Text="Submit" OnClick="SubmitButton_Click" runat="server" />
    <asp:Label ID="ResultLabel" runat="server" />
  </div>
  </form>
</body>
</html>

Tags:

Could not load type 'System.Data.Entity.Design.AspNet.EntityDesignerBuildProvider'

by 21. December 2010 10:51

Make sure you have the assemblies referenced as follows:

<compilation debug="true" targetFramework="4.0">
  <assemblies>
    <add assembly="System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
    <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
    <add assembly="System.Data.Entity.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
  </assemblies>
  <buildProviders>
    <add extension=".edmx" type="System.Data.Entity.Design.AspNet.EntityDesignerBuildProvider" />
  </buildProviders>
</compilation>

Tags:

Asp.Net Get Root Url

by 21. December 2010 07:39

In the page:

<%=RootUrl%><%=ResolveUrl("~/InmanNewsFeedWs.asmx")%>

 

Code behind:

protected string RootUrl
{
  get
  {
    string query = (Request.QueryString == null) ? "" : "?" + Request.QueryString.ToString();
    return Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, string.Empty).Replace(query, string.Empty);
  }
}

Tags:

Welcome to BlogEngine.NET 2.0

by 12. November 2010 21:00

If you see this post it means that BlogEngine.NET 2.0 is running and the hard part of creating your own blog is done. There is only a few things left to do.

Write Permissions

To be able to log in to the blog and writing posts, you need to enable write permissions on the App_Data folder. If you’re blog is hosted at a hosting provider, you can either log into your account’s admin page or call the support. You need write permissions on the App_Data folder because all posts, comments, and blog attachments are saved as XML files and placed in the App_Data folder. 

If you wish to use a database to to store your blog data, we still encourage you to enable this write access for an images you may wish to store for your blog posts.  If you are interested in using Microsoft SQL Server, MySQL, SQL CE, or other databases, please see the BlogEngine wiki to get started.

Security

When you've got write permissions to the App_Data folder, you need to change the username and password. Find the sign-in link located either at the bottom or top of the page depending on your current theme and click it. Now enter "admin" in both the username and password fields and click the button. You will now see an admin menu appear. It has a link to the "Users" admin page. From there you can change the username and password.  Passwords are hashed by default so if you lose your password, please see the BlogEngine wiki for information on recovery.

Configuration and Profile

Now that you have your blog secured, take a look through the settings and give your new blog a title.  BlogEngine.NET 1.4 is set up to take full advantage of of many semantic formats and technologies such as FOAF, SIOC and APML. It means that the content stored in your BlogEngine.NET installation will be fully portable and auto-discoverable.  Be sure to fill in your author profile to take better advantage of this.

Themes and Widgets

One last thing to consider is customizing the look of your blog.  We have a few themes available right out of the box including two fully setup to use our new widget framework.  The widget framework allows drop and drag placement on your side bar as well as editing and configuration right in the widget while you are logged in.  Be sure to check out our home page for more theme choices and downloadable widgets to add to your blog.

Try Out New Features

BlogEngine now supports code syntax highlighting and HTML5 video out of the box. To add a video, click the "Insert video" button just above the post editor. Once your video is uploaded, use the following syntax to show it: [­video src="be-sample.mp4"]. Make sure to add "video/mp4" as a MIME type to your IIS.

You can add formatted code by pressing the "Insert Code" button on the post editor toolbar. Here is a small sample:

// Hello1.cs
public class Hello1
{
   public static void Main()
   {
      System.Console.WriteLine("Hello, World!");
   }
}

 

On the web

You can find BlogEngine.NET on the official website. Here you'll find tutorials, documentation, tips and tricks and much more. The ongoing development of BlogEngine.NET can be followed at CodePlex where the daily builds will be published for anyone to download.

Good luck and happy writing.

The BlogEngine.NET team

Tags: ,

BlogEngine.NET

Asp.Net GetCurrentPageName

by 10. November 2010 18:32

static public string GetCurrentPageName()
{
  System.IO.FileInfo fi = 

    new System.IO.FileInfo(HttpContext.Current.Request.Url.AbsolutePath);
  return fi.Name;
}

 

Tags:

[None]

Outlook 2007 URL Protocol Registry Entry

by 10. November 2010 14:14

Registering Outlook 2007 to a URL Protocol.zip (126.05 kb)

Contents of a registry edit file for 2007:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\outlook]
"URL Protocol"=""
@="URL:Outlook Folders"
[HKEY_CLASSES_ROOT\outlook\DefaultIcon]
@="\"C:\\Program Files\\Microsoft Office\\Office12\\OUTLOOK.EXE\""
[HKEY_CLASSES_ROOT\outlook\shell]
@="open"
[HKEY_CLASSES_ROOT\outlook\shell\open]
@=""
[HKEY_CLASSES_ROOT\outlook\shell\open\command]
@="\"C:\\Program Files\\Microsoft Office\\Office12\\OUTLOOK.EXE\" /select \"%1\""

Modified for 2010 on 64bit machine running Office on x86:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\outlook]
"URL Protocol"=""
@="URL:Outlook Folders"
[HKEY_CLASSES_ROOT\outlook\DefaultIcon]
@="\"C:\\Program Files (x86)\\Microsoft Office\\Office14\\OUTLOOK.EXE\""
[HKEY_CLASSES_ROOT\outlook\shell]
@="open"
[HKEY_CLASSES_ROOT\outlook\shell\open]
@=""
[HKEY_CLASSES_ROOT\outlook\shell\open\command]
@="\"C:\\Program Files (x86)\\Microsoft Office\\Office14\\OUTLOOK.EXE\" /select \"%1\""

Tags:

[None]

Visual Studio 2010 Resources

by 10. November 2010 13:28

The Visual Studio "Productivity Power Tools" are a set of Visual Studio addins that offer enhanced develeper experience in the IDE.  For example, there are features such as the following.  Enhanced tab well, allowing colorization of tabs by file type, alternative tab docking points (i.e. left side vertical tab set, vs. standard top horizontal).  Javascript code auto-collapse regions, similar to the auto-collapse feature on the C#/VB code behind.  Quick find, which allows a more user friendly find/replace, that works similar to a modern web page find (i.e. auto-highliting matches dynamically as you type), along with enhanced regular expression support.  These are just a few examples of some of the great enhanced features provdided in the "Productivity Power Tools". 

To view more details and download the bits, check out this web site: http://visualstudiogallery.msdn.microsoft.com/en-us/d0d33361-18e2-46c0-8ff2-4adea1e34fef

Tags:

[None] | Visual Studio

Windows Phone 7 Development

by 10. November 2010 13:27

Tags:

[None]

MSI Installation Error: The installer was interrupted before <product> could be installed

by 8. November 2010 21:23

Issue: When you run the msi, you get an error 'The installer was interrupted before <product> could be installed.  You need to restart the installer to try again'. 

Solution:

In order to install a web setup project on Windows Server 2008 and IIS 7, you need to install the IIS 6 Metabase Compatibility role service.

 

To install the IIS 6.0 Management Compatibility Components by using the Windows Server 2008 Server Manager

1.     Click Start, click Administrative Tools and then Server Manager.

2.     In the left navigation pane, expand Roles, and then right-click Web Server (IIS) and select Add Role Services.

3.     On the Select Role Services pane, scroll down to IIS 6 Management Compatibility.

4.     Select the check boxes for IIS 6 Metabase Compatibility and IIS 6 Management Console.

5.     Click Next from the Select Role Services pane, and then click Install at the Confirm Installations Selections pane.

6.     Click Close to leave the Add Role Services wizard.

Tags:

[None]

Sample Code Re-write with Generics

by 8. November 2010 15:18

    public string GetCampaign(string campaigncode)

    {

      System.Diagnostics.Debug.WriteLine("inside GetCampaign");

 

      // NEW

      List<campaign> camp = Crm.GetEntityList<campaign>(Crm.BuildStringQuery(

        EntityName.campaign.ToString(), "codename", ConditionOperator.Equal, campaigncode

        , LogicalOperator.And, new string[] { "campaignid", "codename", "name" }));

      return camp.Count == 1 ? camp[0].campaignid.Value.ToString() : "";

 

      // OLD

      ColumnSet cols = new ColumnSet();

      cols.Attributes = new string[] { "campaignid", "codename", "name" };

 

      ConditionExpression[] condition = new ConditionExpression[1];

      condition[0] = new ConditionExpression();

      condition[0].AttributeName = "codename";

      condition[0].Operator = ConditionOperator.Equal;

      condition[0].Values = new string[] { campaigncode };

 

      FilterExpression filter = new FilterExpression();

      filter.FilterOperator = LogicalOperator.And;

      filter.Conditions = condition; //new ConditionExpression[] {condition};

      QueryExpression query = new QueryExpression();

      query.EntityName = EntityName.campaign.ToString();

      query.ColumnSet = cols;

      query.Criteria = filter;

 

      // Retrieve the ServiceAppointments

      BusinessEntityCollection lines = Crm.GetCrmService().RetrieveMultiple(query);

 

      //retrieve into an object

 

      int NumOfLines = lines.BusinessEntities.Length;

      string campid = "";

      System.Diagnostics.Debug.WriteLine("numoflines = " + NumOfLines);

      campaign[] campretrieved = new campaign[NumOfLines];

 

      if (NumOfLines > 1 || NumOfLines < 1)

      {

        System.Diagnostics.Debug.WriteLine("more than one record matched");

        campid = "";

      }

      else

      {

        System.Diagnostics.Debug.WriteLine("found matching contact record");

        int i = 0;

        campid = "";

 

        while (i < 1)

        {

          campretrieved[i] = (campaign)lines.BusinessEntities[i];

          campid = campretrieved[i].campaignid.Value.ToString();

          i++;

        }

      }

      //System.Diagnostics.Debug.WriteLine("campid = " + campid);

      return campid;

    }

 

Tags:

[None]

Invalid postback or callback argument ASP.Net

by 4. November 2010 15:29

Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

This can happen if you are binding a GridView control on page load unconditionally (i.e. it should only be bound when !Page.IsPostBack).

Tags:

ASP.Net

MS CRM Lookup Field DataValue Property JavaScript

by 3. November 2010 17:41

var lookupItem = new Array;

 

// This will get the lookup for the attribute primarycontactid on the Account form.

lookupItem = crmForm.all.primarycontactid.DataValue;

 

// If there is data in the field, show it in a series of alerts.

if (lookupItem != null)

{

   // The text value of the lookup.

   alert(lookupItem[0].name);

 

   // The GUID of the lookup.

   alert(lookupItem[0].id);

 

   // The entity type name.

   alert(lookupItem[0].typename);

 

   // The entity type code of the lookup: 1=account, 2= contact.

   // This attribute is deprecated. Use typename instead.

   alert(lookupItem[0].type);

}

 

 

Tags:

[None]