Joseph Michael Pesch
VP Programming

C# Code to Toggle Through Open Windows

by 28. June 2010 16:56

This code is designed to allow user to define multiple open windows (by specifying the window title) and a duration for which to display each.  When you start the process it will toggle through those windows for the desired duration and then start back at the first window until the process is stopped.

Below is the primary code, the full project is available in the attached zip file.

ToggleWindows.zipx (67.88 kb)

using System;

using System.Windows.Forms;

using System.Runtime.InteropServices;

using System.Threading;

using System.Data;

 

namespace ToggleWindows

{

  public partial class ToggleWindows : Form

  {

    public ToggleWindows()

    {

      InitializeComponent();

    }

 

    System.Threading.Thread thread;

 

    [DllImport("user32.dll")]

    public static extern Int32 SetForegroundWindow(int hWnd);

    [DllImport("user32.dll")]

    public static extern int FindWindow(string lpClassName, string lpWindowName);

 

    private static void BringToFront(string className, string CaptionName)

    {

      SetForegroundWindow(FindWindow(className, CaptionName));

    }

 

    private bool Toggle { get; set; }

    private void StartToggle()

    {

      int irow = 0;

      int irows = this.SettingsDataGridView.Rows.Count;

      int irowX = 0;

      while (Toggle)

      {

        if (irow >= irows) irow = 0;

        if (this.SettingsDataGridView.Rows[irow].Cells[0].Value == null

          || this.SettingsDataGridView.Rows[irow].Cells[0].Value.ToString() == "")

        {

          irow++;

          continue;

        }

        this.SettingsDataGridView.Rows[irowX].Selected = false;

        irowX = irow;

        this.SettingsDataGridView.Rows[irow].Selected = true;

        string title = this.SettingsDataGridView.Rows[irow].Cells[0].Value.ToString();

        int duration = Convert.ToInt32(this.SettingsDataGridView.Rows[irow].Cells[1].Value);

        System.Diagnostics.Debug.WriteLine(duration + ":" + title);

        BringToFront(null, title);

        Thread.Sleep(duration * 1000);

        irow++;

      }

    }

    private void StopToggle()

    {

      Toggle = false;

      thread.Abort();

    }

 

    private void ToggleWindows_Load(object sender, EventArgs e)

    {

      string uri = Application.StartupPath + @"\Settings.xml";

      DataSet ds = new DataSet();

      ds.ReadXml(uri);

      this.SettingsDataGridView.DataSource = ds.Tables[0];

      this.SettingsDataGridView.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

      ds.Dispose();

    }

 

    private void SaveData()

    {

      string uri = Application.StartupPath + @"\Settings.xml";

      DataSet ds = new DataSet();

      ds.ReadXml(uri);

      DataRow drow = ds.Tables[0].NewRow();

      ds.Tables[0].Rows.Clear();

      int count = 0;

      foreach (DataGridViewRow row in this.SettingsDataGridView.Rows)

      {

        if (row.Cells[0].Value == null || row.Cells[0].Value.ToString() == "") continue;

        count++;

        drow["Title"] = row.Cells[0].Value.ToString();

        drow["Duration"] = row.Cells[1].Value.ToString();

        ds.Tables[0].Rows.Add(drow);

        drow = ds.Tables[0].NewRow();

      }

      ds.WriteXml(uri);

      ds.Dispose();

      MessageBox.Show("Saved " + count + " rows of data.");

    }

 

    private void saveToolStripMenuItem_Click(object sender, EventArgs e)

    {

      SaveData();

    }

 

    private void startToolStripMenuItem_Click(object sender, EventArgs e)

    {

      Toggle = true;

      thread = new Thread(new ThreadStart(StartToggle));

      thread.Start();

    }

 

    private void stopToolStripMenuItem_Click(object sender, EventArgs e)

    {

      StopToggle();

    }

 

  }

}

 

Tags:

[None]

Perform Content Replace on Each File in Folder

by 27. June 2010 23:46

using System.IO;

 

namespace FileIO

{

  class Program

  {

    static void Main(string[] args)

    {

      string[] fileEntries = Directory.GetFiles(@"C:\JMPBlog\App_Data\posts");

      foreach (string fileName in fileEntries)

      {

        string fileContents = File.ReadAllText(fileName)

          .Replace("href=\"~/file.axd", "href=\"JMP/Blog/file.axd")

          .Replace("src=\"~/image.axd", "src=\"JMP/Blog/image.axd");

        if(fileContents.Contains("image.axd"))

          System.Diagnostics.Debug.WriteLine("found");

        File.WriteAllText(fileName, fileContents);

      }

 

    }

  }

}

 

Using BlogEngine.net made the below modifications to allow it to run in sub-directory of root website.

 

 

Admin/Pages/Pages.aspx.cs

 

private void btnUploadImage_Click(object sender, EventArgs e)

{

  string relativeFolder = DateTime.Now.Year.ToString() + Path.DirectorySeparatorChar + DateTime.Now.Month.ToString() + Path.DirectorySeparatorChar;

  string folder = BlogSettings.Instance.StorageLocation + "files" + Path.DirectorySeparatorChar;

  string fileName = txtUploadImage.FileName;

  Upload(folder + relativeFolder, txtUploadImage, fileName);

  // JMP: Added ~ to front of url to make it relative to the root of the application

  string path = Utils.RelativeWebRoot.ToString();

  string img = string.Format("<img src=\"~/{0}image.axd?picture={1}\" alt=\"\" />", path, Server.UrlEncode(relativeFolder.Replace("\\", "/") + fileName));

  txtContent.Text += img;

}

 

private void btnUploadFile_Click(object sender, EventArgs e)

{

  string relativeFolder = DateTime.Now.Year.ToString() + Path.DirectorySeparatorChar + DateTime.Now.Month.ToString() + Path.DirectorySeparatorChar;

  string folder = BlogSettings.Instance.StorageLocation + "files" + Path.DirectorySeparatorChar;

  string fileName = txtUploadFile.FileName;

  Upload(folder + relativeFolder, txtUploadFile, fileName);

  // JMP: Added ~ to front of url to make it relative to the root of the application

  string a = "<p><a href=\"~/{0}file.axd?file={1}\">{2}</a></p>";

  string text = txtUploadFile.FileName + " (" + SizeFormat(txtUploadFile.FileBytes.Length, "N") + ")";

  txtContent.Text += string.Format(a, Utils.RelativeWebRoot, Server.UrlEncode(relativeFolder.Replace("\\", "/") + fileName), text);

}

 

 

Tags:

BlogEngine.NET | C#

Microsoft Dynamics CRM

by 23. June 2010 14:39

The platform is the heart of the Microsoft Dynamics CRM system. When you use the Microsoft Dynamics CRM SDK, you are building on top of this system. The Microsoft Dynamics CRM platform supports smaller deployments and can scale for application service provider models also. The security mode protects the platform from unauthorized access across the Web. The main platform components are as follows:

  • Microsoft SQL Server database
  • Web services
  • System services (workflow, metadata, and integration)
  • A query processor that supports the entity model
  • Secured ad hoc queries that use an XML fetch statement to protect the physical database
  • Plug-ins for business logic extensibility
  • Reporting services

When you develop an application that uses the Microsoft Dynamics CRM server, you use Web services to communicate with the underlying platform layer. The server platform is responsible for creating domain-specific objects. In Microsoft Dynamics CRM, these objects include contact, lead, opportunity, account, business unit, and more. The goal of the platform is to implement the service-specific rules by manipulating and combining the underlying domain objects.The platform does not impose business-specific logic. This layer imposes only generic domain constraints. It contains the building blocks for an application, but by itself is nothing more than a collection of related objects. However, the interaction between those objects within the domain can be assumed to implement more extensible logic such as the quote-to-order-to-invoice processing and pricing logic.The server platform also controls access to objects through security, controls access to the database, and raises events for workflow processes and custom business logic implementations. The platform layer provides for both incoming and outgoing e-mail processing through Microsoft Exchange.I am attaching the following so you have access to as much information as you hopefully need to make your decisions:

  1. Whitepaper on the port recommendations for CRM:
  2. Internet Facing Deployment setup document (how to make CRM available to AD users publically):
  3. CRM Dynamics planning guide – see chapter 4 for server topology examples:

A simple version of the diagram on page 4-64 of this guide would have sql server to house the database schema, and ssrs on a server(s) (which can be the same as the SQL database server, or on a separate server). CRM app and web on another, a trust would need to be made between the two so they can talk.  The CRM application server would need to talk to a domain controller for authentication, and the CRM server would have an SSL cert for encryption so that the IFD can be used.  There is an installable application for the CRM server that allows the reports from the SSRS server to run through the CRM application.  Sharepoint would be utilized in an iFrame embedded for document storage, not for rendering reports.  SSRS will be used to render reports through CRM.

Tags:

[None]

jQuery .dialog() Issue with ASP.Net Postback Values Not Available

by 21. June 2010 16:15

When using jQuery .dialog() (from the UI framework), you can have an issue where the field values are not retained on the form post back.  To solve this issue you need to append the dialog object into the html form object as shown below.  In my case when I did not have the dlg.parent().appendTo() call my server controls that were contained inside the dialog div would have there values reset.  So trying to retreive the values that the user selected would not be possible on a post back.

var dlg = $("#MyDialogDiv").dialog({ modal: true });

dlg.parent().appendTo($("form:first"));

 

Tags:

[None]

ASP.Net FindControl Recursive

by 16. June 2010 22:33

  public static Control FindControlRecursive(Control Root, string CtlID)

  {

    if (Root.ID == CtlID)

      return Root;

    foreach (Control ctl in Root.Controls)

    {

      Control Ctl = FindControlRecursive(ctl, CtlID);

      if (Ctl != null)

        return Ctl;

    }

    return null;

  }

 

Tags:

[None]

C# Activate Window (Simulate Alt Tab Window)

by 16. June 2010 20:30

 

using System;

using System.Runtime.InteropServices;

 

namespace ActivateWindowConsoleApplication

{

  class Program

  {

    [DllImport("user32.dll")]

    public static extern Int32 SetForegroundWindow(int hWnd);

    [DllImport("user32.dll")]

    public static extern int FindWindow(string lpClassName, string lpWindowName);

 

    private static void BringToFront(string className, string CaptionName)

    {

      SetForegroundWindow(FindWindow(className, CaptionName));

    }

 

    static void Main(string[] args)

    {

        BringToFront(null, "Doc1.txt - Notepad");

        Thread.Sleep(3000);

        BringToFront(null, "Sent Items - Microsoft Outlook");

        Thread.Sleep(3000);

        BringToFront(null, "Doc3.txt - Notepad");

        Thread.Sleep(3000);

    }

  }

}

Tags:

[None]

SQL Script to Search All Tables and Columns for Text String

by 15. June 2010 16:19

This sript will search all columns of all tables in the database and look for matching text as entered in the @SearchStr variable.


set nocount on

 

declare

  @SearchStr nvarchar(1000)

, @SearchStr2 nvarchar(110)

, @TableName nvarchar(256)

, @ColumnName nvarchar(128)

 

set @SearchStr = 'Search text here...'

set @SearchStr2 = quotename('%' + @SearchStr + '%','''')

set @TableName = ''

 

create table #Results

(

  ColumnName nvarchar(370)

, ColumnValue nvarchar(3630)

)

 

while @TableName is not null begin

  set @ColumnName = ''

  set @TableName =

  (

     select min(quotename(TABLE_SCHEMA)

                + '.'

                + quotename(TABLE_NAME))

     from INFORMATION_SCHEMA.TABLES

     where TABLE_TYPE = 'BASE TABLE'

     and quotename(TABLE_SCHEMA)

         + '.'

         + quotename(TABLE_NAME)

         > @TableName

     and objectproperty(object_id(quotename(TABLE_SCHEMA)

                                  + '.'

                                  + quotename(TABLE_NAME)

                                  ), 'IsMSShipped') = 0

    ) -- set @TableName

  while (@TableName is not null) and(@ColumnName is not null) begin

    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('char', 'varchar', 'nchar', 'nvarchar')

      and quotename(COLUMN_NAME) > @ColumnName

    )

    if @ColumnName is not null begin

      insert into #Results

      exec

      (

         'select ''' + @TableName

          + '.'

          + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)

         from ' + @TableName + ' (NOLOCK)

         where ' + @ColumnName + ' LIKE ' + @SearchStr2

       )

    end

  end

end

select ColumnName, ColumnValue from #Results

drop table #Results

 

 

 

Tags:

SQL Server

Access Master Page Class Object, Public Properties, etc.

by 15. June 2010 15:22

If you include the <%@ MasterType VirtualPath="~/Site.master" %>  declaration in your page, you can then access the master page class using "Master." reference as shown in example below. 

 

… Site.master.cs …

public partial class SiteMaster : System.Web.UI.MasterPage

{

  public string ShowClass { get; set; }

  public string HideClass { get; set; }

}

 
… Sample.aspx …

<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Sample.cs" Inherits="Sample" %>

<%@ MasterType VirtualPath="~/Site.master" %>

 

 
… Sample.aspx.cs …

protected void Page_Load(object sender, EventArgs e)

{

  Master.ShowClass = ".Refinance";

  Master.HideClass = ".Purchase";

}

IMPORTANT NOTE: When running a file system based web site you must make sure the master page code file is placed in the "APP_CODE" folder, otherwise, the properties/methods will not be accessible from other pages.

Tags:

[None]

Include Files with Absolute Path on Master Page Files

by 11. June 2010 13:26

Use Page_Init event to load file references into the html page header: 

Page.Header.Controls.Add(new LiteralControl(@"<script src='" + ResolveUrl("~/jQuery/js/jquery-1.4.2.min.js") + "' type='text/javascript'></script>\r\n"));

Page.Header.Controls.Add(new LiteralControl(@"<link href='" + ResolveClientUrl("~/css/MyStyles.css") + "' rel='stylesheet' type='text/css' />\r\n"));

Tags:

[None]

Command to Force Windows to Shutdown without Waiting

by 8. June 2010 20:09

Command Prompt:

shutdown -r -t 0

(that is number zero for last parameter)

Tags:

[None]

Search Engine Submissions

by 8. June 2010 14:26

Tags:

[None]

Pasting Formatted Text from Visual Studio into BlogEngine.net

by 4. June 2010 21:50

 How to paste formatted text from Visual Studio (or SQL Management Studio) into BlogEngine.net without and retain color, indentation, etc.

  1. Copy from Visual Studio
  2. Paste into Word document
  3. Copy from Word document
  4. Paste into BlogEngine.net normal edit window
  5. Click the "HTML" view button
  6. Click the "Update" button from the HTML view
  7. Enjoy!!!

Tags:

[None]

jQuery Web Service Call

by 4. June 2010 21:27

JQueryWebService.zipx (39.62 kb)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!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 src="jQuery/jquery-1.4.2.js" type="text/javascript"></script>

 

  <style type="text/css">

    body

    {

      font-family: Verdana, Tahoma, Calibri;

    }

    .ProcessingAni

    {

      display: none;

    }

  </style>

</head>

<body>

  <table>

    <tr>

      <td>

        First Name:

      </td>

      <td>

        <input type="text" id="FirstNameTextBox" value="Joe" style="width: 50px;" />

      </td>

    </tr>

    <tr>

      <td>

        Last Name:

      </td>

      <td>

        <input type="text" id="LastNameTextBox" value="Pesch" style="width: 50px;" />

      </td>

    </tr>

    <tr>

      <td colspan="2">

        <input type="button" id="WebServiceCallButton" value="Run Web Service" onclick="WebServiceCall();" />

        <img src="images/ProcessingAni.gif" class="ProcessingAni" alt="Processing..." />

        <span class="ProcessingAni" style="margin-left: 15px;">Processing...</span>

      </td>

    </tr>

  </table>

 

  <script type="text/javascript">

    function WebServiceCall() {

      $('.ProcessingAni').show();

      $('#WebServiceCallButton').hide();

      $.ajax({

        type: "POST",

        url: "SampleWS.asmx/HelloYou",

        data: "{'FirstName':"

        + "'" + $('#FirstNameTextBox').val() + "'"

        + ",'LastName':"

        + "'" + $('#LastNameTextBox').val() + "'"

        + "}",

        contentType: "application/json; charset=utf-8",

        dataType: "json",

        success: function(msg) {

          alert(msg.d);

          $('.ProcessingAni').hide();

          $('#WebServiceCallButton').show();

        }

        },
        error: function (request, status, error) {
          alert(request.responseText);
        }

 

    }

  </script>

 

  <form id="form1" runat="server">

  <div>

  </div>

  </form>

</body>

</html>

 

 

Tags:

[None]

Visual Studio 2005 Business Intelligence Studio Can't Open SSIS Script Task

by 4. June 2010 18:16

SSIS package that’s developed in Microsoft Visual Studio 2005 may have a script task inside that doesn’t open when you click on the "Design Script" button.  In my case this was after I installed SQL Server 2008 locally. I had to re-install SQL Server 2005 sp2 (after installing SQL Server 2008) and then the script tasks are ok again.

Tags:

Oracle | SSIS | Visual Studio