Joseph Michael Pesch
VP Programming

C# ArrayList to Delimited String

by 31. May 2011 09:18
// Convert ArrayList to comma delimited string...
string myListString = string.Join(","
        , ((myArrayList.ToArray(typeof(string)) as string[]);

Tags:

C#

LDAP Query to Find a Users Manager Using C#

by 28. May 2011 11:46

Method 1:

DirectoryEntry deUserRootEntry = new DirectoryEntry("LDAP://impaccompanies.com");
DirectorySearcher dsUserSearcher = new DirectorySearcher();
dsUserSearcher.SearchRoot = deUserRootEntry;
//dsUserSearcher.Filter = "name=User Name";
dsUserSearcher.Filter = "userprincipalname=userid@domain.com";
if (dsUserSearcher.FindOne().GetDirectoryEntry() != null)
{
  DirectoryEntry deUser = dsUserSearcher.FindOne().GetDirectoryEntry();

  if (dsUserSearcher.FindOne().GetDirectoryEntry().Properties["manager"].Value != null)
  {
    ///you get manager here...
  }
}

Method 2:

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

// Get specific user in domain...
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain.com");
UserPrincipal usp = UserPrincipal.FindByIdentity(ctx, "userid@domain.com");

// Call the GetManager method and get the managers user id...
UserPrincipal mgp = GetManager(ctx, usp);
System.Diagnostics.Debug.WriteLine(mgp.UserPrincipalName);

// Method to find the manager for a specific user...
public UserPrincipal GetManager(PrincipalContext ctx, UserPrincipal user)
{
  if (user != null)
  {
    // Get the DirectoryEntry object of the UserPrincipal object
    var dirEntryForUser = user.GetUnderlyingObject() as DirectoryEntry;

    if (dirEntryForUser != null)
    {
      // See if the user has a manager assigned and if so return it...
      if (dirEntryForUser.Properties["manager"] != null 
          && dirEntryForUser.Properties["manager"].Count > 0)
      {
        string mgrDN = dirEntryForUser.Properties["manager"][0].ToString();
        // Get the manager UserPrincipal via the DN 
        return UserPrincipal.FindByIdentity(ctx, mgrDN);
      }
    }
  }
  return null;
}

Tags:

C#

LDAP Query to Find a Users Manager Using C#

by 28. May 2011 11:28

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

// Get specific user in domain...
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain.com");
UserPrincipal usp = UserPrincipal.FindByIdentity(ctx, "userid@domain.com");

// Call the GetManager method and get the managers user id...
UserPrincipal mgp = GetManager(ctx, usp);
System.Diagnostics.Debug.WriteLine(mgp.UserPrincipalName);

// Method to find the manager for a specific user...
public UserPrincipal GetManager(PrincipalContext ctx, UserPrincipal user)
{
  if (user != null)
  {
    // Get the DirectoryEntry object of the UserPrincipal object
    var dirEntryForUser = user.GetUnderlyingObject() as DirectoryEntry;

    if (dirEntryForUser != null)
    {
      // See if the user has a manager assigned and if so return it...
      if (dirEntryForUser.Properties["manager"] != null 
          && dirEntryForUser.Properties["manager"].Count > 0)
      {
        string mgrDN = dirEntryForUser.Properties["manager"][0].ToString();
        // Get the manager UserPrincipal via the DN 
        return UserPrincipal.FindByIdentity(ctx, mgrDN);
      }
    }
  }
  return null;
}

Tags:

C# | LDAP

Sharepoint Get User Information from within Workflow/Application Page

by 27. May 2011 14:39

// Workflow member variable declarations...
public Guid workflowId = default(System.Guid);
public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();

private void SomeMethod()
{
  // This method failed: SPList userList = SPContext.Current.Web.SiteUserInfoList;
  SPList userList = workflowProperties.Site.RootWeb.SiteUserInfoList;
  SPUser user = SPContext.Current.Web.EnsureUser(@"domain\userid");
  SPListItem userItem = userList.Items.GetItemById(user.ID);
  foreach(SPField fld in userItem.Fields) 
  {
    System.Diagnostics.Debug.WriteLine(string.Format("{0} >>> {1}", fld.Title, fld.InternalName)); 
  }
}

OUTPUT FROM MY SAMPLE TEST:
ID >>> ID
Content Type ID >>> ContentTypeId
Content Type >>> ContentType
Name >>> Title
Modified >>> Modified
Created >>> Created
Created By >>> Author
Modified By >>> Editor
Has Copy Destinations >>> _HasCopyDestinations
Copy Source >>> _CopySource
owshiddenversion >>> owshiddenversion
Workflow Version >>> WorkflowVersion
UI Version >>> _UIVersion
Version >>> _UIVersionString
Attachments >>> Attachments
Approval Status >>> _ModerationStatus
Approver Comments >>> _ModerationComments
Edit >>> Edit
Name >>> LinkTitleNoMenu
Title >>> LinkTitle
Title >>> LinkTitle2
Select >>> SelectTitle
Instance ID >>> InstanceID
Order >>> Order
GUID >>> GUID
Workflow Instance ID >>> WorkflowInstanceID
URL Path >>> FileRef
Path >>> FileDirRef
Modified >>> Last_x0020_Modified
Created >>> Created_x0020_Date
Item Type >>> FSObjType
Sort Type >>> SortBehavior
Effective Permissions Mask >>> PermMask
Name >>> FileLeafRef
Unique Id >>> UniqueId
Client Id >>> SyncClientId
ProgId >>> ProgId
ScopeId >>> ScopeId
File Type >>> File_x0020_Type
HTML File Type >>> HTML_x0020_File_x0020_Type
Edit Menu Table Start >>> _EditMenuTableStart
Edit Menu Table Start >>> _EditMenuTableStart2
Edit Menu Table End >>> _EditMenuTableEnd
Name >>> LinkFilenameNoMenu
Name >>> LinkFilename
Name >>> LinkFilename2
Type >>> DocIcon
Server Relative URL >>> ServerUrl
Encoded Absolute URL >>> EncodedAbsUrl
File Name >>> BaseName
Property Bag >>> MetaInfo
Level >>> _Level
Is Current Version >>> _IsCurrentVersion
Item Child Count >>> ItemChildCount
Folder Child Count >>> FolderChildCount
Account >>> Name
E-Mail >>> EMail
Mobile Number >>> MobilePhone
About Me >>> Notes
SIP Address >>> SipAddress
Locale >>> Locale
Calendar Type >>> CalendarType
AdjustHijriDays >>> AdjustHijriDays
TimeZone >>> TimeZone
Time Format >>> Time24
Alternate Calendar Type >>> AltCalendarType
CalendarView Options >>> CalendarViewOptions
WorkDays >>> WorkDays
WorkDay StartHour >>> WorkDayStartHour
WorkDay EndHour >>> WorkDayEndHour
Is Site Admin >>> IsSiteAdmin
Deleted >>> Deleted
Picture >>> Picture
Department >>> Department
Job Title >>> JobTitle
Is Active >>> IsActive
Group >>> GroupLink
Edit >>> GroupEdit
Name >>> ImnName
Picture >>> PictureDisp
Name >>> NameWithPicture
Name >>> NameWithPictureAndDetails
Edit >>> EditUser
Selection Checkbox >>> UserSelection
Content Type >>> ContentTypeDisp
 
 

Tags:

C# | Sharepoint

Sharepoint Get User Information from within Workflow/Application Page

by 27. May 2011 13:51

SPList userList = SPContext.Current.Web.SiteUserInfoList;

SPUser user = SPContext.Current.Web.EnsureUser(@"domain\userid");

SPListItem userItem = userList.Items.GetItemById(user.ID);

 

 

Tags:

C# | Sharepoint

Linq to Sharepoint DataContext Binding

by 27. May 2011 07:32

// Get DataContext from application page

SPMetalDataContext data = new SPMetalDataContext(SPContext.GetContext(this.Context).Web.Url);

 

// Get DataContext from workflow

public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();

// The workflowProperties variable would be declared in the workflow class

SPMetalDataContext data = new SPMetalDataContext(workflowProperties.Item.Web.Url); 

 

OR

SPMetalDataContext data = new SPMetalDataContext(SPContext.Current.Web.Url);

 

Tags:

C# | Sharepoint

Linq Child/Nested Entity Join to Master Table Entity

by 26. May 2011 10:13
    private void LoadList_AssignedResources(int RequestId)
    {
      using (SPMetalDataContext dc = new SPMetalDataContext(this.Web.Url))
      {

        ResourceRequestsItem req = dc.ResourceRequests
          .Where(x => x.Id.Equals(RequestId)).FirstOrDefault();
        
        var qry = from rs in dc.Resources
                  join rx in req.Resources on rs.Id equals rx.Id
                  select new
                  {
                    Title = rs.Title,
                    Id = rs.Id
                  };

        AssignedResourcesList.DataTextField = "Title";
        AssignedResourcesList.DataValueField = "Id";
        AssignedResourcesList.DataSource = qry;
        AssignedResourcesList.DataBind();
      }
    }

Tags:

C# | LINQ to SQL

Add Author, Created, Editor and Modified Fields to SPMetal Generated C# Class for Sharepoint

by 26. May 2011 09:29
public partial class Item : Microsoft.SharePoint.Linq.ITrackEntityState
  , Microsoft.SharePoint.Linq.ITrackOriginalValues
  , System.ComponentModel.INotifyPropertyChanged
  , System.ComponentModel.INotifyPropertyChanging
{
  // Add the following to the Item class in the SPMetal generated class...
  string _CreatedBy;
  [Microsoft.SharePoint.Linq.ColumnAttribute(Name = "Author", Storage = "_CreatedBy"
    , ReadOnly = true, FieldType = "User", IsLookupValue = true)]
  public string CreatedBy
  {
    get
    { return this._CreatedBy; }
    set
    {
      if ((value != this._CreatedBy))
      {
        this.OnPropertyChanging("CreatedBy"this._CreatedBy);
        this._CreatedBy = value;
        this.OnPropertyChanged("CreatedBy");
      }
    }
  }

  DateTime _CreatedOn;
  [Microsoft.SharePoint.Linq.ColumnAttribute(Name = "Created", Storage = "_CreatedOn"
    , ReadOnly = true, FieldType = "DateTime", IsLookupValue = false)]
  public DateTime CreatedOn
  {
    get
    { return this._CreatedOn; }
    set
    {
      if ((value != this._CreatedOn))
      {
        this.OnPropertyChanging("CreatedOn"this._CreatedOn);
        this._CreatedOn = value;
        this.OnPropertyChanged("CreatedOn");
      }
    }
  }

  string _ModifiedBy;
  [Microsoft.SharePoint.Linq.ColumnAttribute(Name = "Editor", Storage = "_ModifiedBy"
    , ReadOnly = true, FieldType = "User", IsLookupValue = true)]
  public string ModifiedBy
  {
    get
    {
      return this._ModifiedBy;
    }
    set
    {
      if ((value != this._ModifiedBy))
      {
        this.OnPropertyChanging("ModifiedBy"this._ModifiedBy);
        this._ModifiedBy = value;
        this.OnPropertyChanged("ModifiedBy");
      }
    }
  }

  DateTime _ModifiedOn;
  [Microsoft.SharePoint.Linq.ColumnAttribute(Name = "Modified", Storage = "_ModifiedOn"
    , ReadOnly = true, FieldType = "DateTime", IsLookupValue = false)]
  public DateTime ModifiedOn
  {
    get
    {
      return this._ModifiedOn;
    }
    set
    {
      if ((value != this._ModifiedOn))
      {
        this.OnPropertyChanging("ModifiedOn"this._ModifiedOn);
        this._ModifiedOn = value;
        this.OnPropertyChanged("ModifiedOn");
      }
    }
  }

Tags:

C# | Sharepoint

Simple Linq In Clause Example

by 25. May 2011 09:43
      // Sample using array and string converted to array...
      string[] ValueArray = new string[] { "11""13" };
      string ValueList = "1;3;5;9;15";
      using (SPMetalDataContext dc = new SPMetalDataContext(this.Web.Url))
      {
        var query =
          from res in dc.Resources
          where ValueList.Split(';').Contains(res.Id.ToString())
             || ValueArray.Contains(res.Id.ToString())
          select new
          {
            res.Title,
            res.Id
          };

Tags:

C#

C# Application to Toggle Between Multiple Windows for Specified Time Interval

by 19. May 2011 08:12

This application allows you to define windows with intervals and then when started it will toggle between those windows at the specified interval.

 

ToggleWindows.zipx (70.15 kb)

Tags:

C# | Windows

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#

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

C# Character Code Example

by 24. October 2010 13:27

for (int i = 48; i <= 57; i++) // 0 through 9

  System.Diagnostics.Debug.WriteLine((char)i);

for (int i = 65; i <= 90; i++) // A through Z

  System.Diagnostics.Debug.WriteLine((char)i);

for (int i = 97; i <= 122; i++) // a through z

  System.Diagnostics.Debug.WriteLine((char)i);

 

Tags:

C#

Using HTTPRuntime.Cache in Non-Web Application

by 31. August 2010 23:32

Sample Code:

using System;

using System.Web;

using System.Web.Caching;

using System.Threading;

 

namespace HTTPCacheSample

{

  classProgram

  {

 

    #region HTTP Runtime Cache

 

    privatestaticHttpRuntime httpRuntime;

    privatestaticvoid EnsureHttpRuntime()

    {

      System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString()

        + ": EnsureRuntime...");

      if (null == httpRuntime)

      {

        // Create an Http Content to give us access to the cache.

        httpRuntime = newHttpRuntime();

        System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString()

          + ": null httpRuntime... creating new instance");

      }

    }

    publicstaticCache Cache

    {

      get

      {

        EnsureHttpRuntime();

        System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString()

          + ": return HttpRuntime.Cache...");

        returnHttpRuntime.Cache;

      }

    }

 

    #endregion

 

    staticvoid Main(string[] args)

    {

      Cache.Add("TestCache", "This is a test @" + DateTime.Now.ToString()

        , null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration

        , CacheItemPriority.High, null);

      for (int i = 0; i <= 10; i++)

      {

        ThreadStart threadDelegate = newThreadStart(TestIt);

        Thread newThread = newThread(threadDelegate);

        newThread.Start();

      }

      Console.Title = "HTTPCacheSample";      Console.ReadLine();

    }

 

    staticvoid TestIt()

    {

      Console.WriteLine(Cache["TestCache"].ToString());

    }

 

  }

}

Console Output:

Diagnostics Output:

8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: null httpRuntime... creating new instance
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: EnsureRuntime...
The thread '<No Name>' (0x119c) has exited with code 0 (0x0).
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
The thread '<No Name>' (0x4ac) has exited with code 0 (0x0).
The thread '<No Name>' (0x21c0) has exited with code 0 (0x0).
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
The thread '<No Name>' (0xedc) has exited with code 0 (0x0).
The thread '<No Name>' (0x1a88) has exited with code 0 (0x0).
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
The thread '<No Name>' (0x1e04) has exited with code 0 (0x0).
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
The thread '<No Name>' (0x21a8) has exited with code 0 (0x0).
The thread '<No Name>' (0x20dc) has exited with code 0 (0x0).
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
8/31/2010 5:43:34 PM: EnsureRuntime...
8/31/2010 5:43:34 PM: return HttpRuntime.Cache...
The thread '<No Name>' (0x74) has exited with code 0 (0x0).
The thread '<No Name>' (0x1cb4) has exited with code 0 (0x0).
The thread '<No Name>' (0x1da4) has exited with code 0 (0x0).

Tags:

ASP.Net | C#

Override Application Settings C#

by 31. August 2010 17:18

When you create/edit application settings via the projects properties window in Visual Studio (as shown in screen shot below), it will create app/web.config entries (as shown below in sample .config entry below).  However, if you change those entries in the .config file on a deployed app/web instance, you may notice the updated .config values are not actually being used by the application/web when it runs.  In order to have the application/web use the values from your .config file you can write a custom handler (as shown in the sample code below).

Screen shot of properties dialog:

Sample of .config values entered via the propeties dialog:

<applicationSettings> 

  <MyApplication.Properties.Settings> 

    <settingname="MyUserSetting"serializeAs="String">

      <value>white</value>

    </setting>

  </ MyApplication.Properties.Settings>

</applicationSettings>

Sample of code to override the property:

<appSettings>

  <add key="MyackgroundColor"value="white"/>

</appSettings>

 

 

using System;

using System.Configuration;

using System.Drawing;

 

publicclass MyUserSettings : ApplicationSettingsBase

{

  [ApplicationScopedSetting()]

  [DefaultSettingValue("white")]

  public Color BackgroundColor //Note: property name (i.e. BackgroundColor) is arbitrary

  {

    get

    {

      return ((Color)ConfigurationManager.AppSettings["MyBackgroundColor"]);

    }

    set

    {

      this["BackgroundColor"] = (Color)value;

    }

  }

}

 

 

Tags:

ASP.Net | C#

Open Source PDF Generator iTextSharp

by 23. July 2010 17:19

iTextSharp-SampleC#WebSite.zipx (2.49 mb)

itextsharp-5.0.6-dll.zip (1.19 mb)

Sample code to populate form fields in template and save as new document (via C# web page):

using System;

using System.IO;

using iTextSharp.text.pdf;

 

publicpartialclassFillFormFields : System.Web.UI.Page

{

  protectedvoid Page_Load(object sender, EventArgs e)

  {

    GeneratePDF();

  }

 

  protectedvoid GeneratePDF()

  {

    // Setup the output file

    string pdfOutputFilePath = @"Output\FillFormFields-"

      + DateTime.Now.ToString()

      .Replace("/", "_")

      .Replace(":", "_")

      .Replace(" ", "_")

      + ".pdf";

    FileStream pdfOutputFile

      = newFileStream(Server.MapPath(pdfOutputFilePath)

        , FileMode.Create, FileAccess.ReadWrite);

    // Load the template file

    PdfReader pdfReader = newPdfReader(Server.MapPath(@"Templates\FillFormFields.pdf"));

    PdfStamper pdfStamper = null;

    pdfStamper = newPdfStamper(pdfReader, pdfOutputFile);

    // Get the form fields object

    AcroFields pdfForm = pdfStamper.AcroFields;

    // Fill the form fields with data

    pdfForm.SetField("Lead.LastAction.Date", DateTime.Now.ToString("MMMM dd, yyyy"));

    // Close the documents

    pdfStamper.FormFlattening = true;

    pdfStamper.Close();

    pdfReader.Close();

  }

}

 

 

 

Tags:

ASP.Net | C#

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#

Linq To SQL Error: Cannot access a disposed object.

by 17. March 2010 14:06

Cannot access a disposed object. Object name: 'DataContext accessed after Dispose.'.  This can happen if you send a Linq query result entity out of a procedure as shown below.  The issues is that the inner procedure has not actually evaluated the query (i.e. results have not been retrieved from the SQL server, just the construct for the query exists).  When you leave the inner procedure and attempt to access the data within the outer procedure the database context is gone (since it was wrapped in a using statement).  Only at the point when you attempt to access the data members will the actual query results be requested from the SQL server and at that point there is no database context under which to execute the query.  You may get the process to work by removing the using statement; however, that is not a correct practice.  The better solution is to return an IEnumerable list using the .ToList() method on the result entity you are returning.  This will force the query to execute and the full result set will be populated into the returned list.

Outer Procedure Code:
...
   IEnumerable<BidMortgage.BMObject.LowestBid> bids = BidMortgage.BMObject.GetLowestBids();

   /* Error here if not using .ToList<>() */
   foreach (BidMortgage.BMObject.LowestBid bid in bids)
{
...}
...

 


Inner Procedure Code:

public class LowestBid

{

   public LowestBid()

   {

   }

   public int LoanTypeID { get; set; }

   public string LoanTypeName { get; set; }

   public decimal CalculatedAPR { get; set; }

   public decimal InterestRate { get; set; }

}

 

 

public static IEnumerable<LowestBid> GetLowestBids()

{

  DataTable tbl = new DataTable();

  try

  {

    using (BidMortgage.BidMortgageDataContext db = new BidMortgageDataContext())

    return (from row in db.LoanRequestBids

    group row by row.tbl_LoanRequest.LoanTypeID

    into g

    select new LowestBid

    { LoanTypeID = g.Key

      , LoanTypeName = (from itm in db.ListValues_MortgageTypes

                        where itm.TypeValue == g.Key

                        select itm.TypeName).SingleOrDefault()

      , CalculatedAPR = g.Min(t => t.CalculatedAPR)

      , InterestRate = (from itm in db.LoanRequestBids

                        where itm.CalculatedAPR == g.Min(t => t.CalculatedAPR)

                        && itm.tbl_LoanRequest.LoanTypeID == g.Key

                        select itm.InterestRate).SingleOrDefault()

    }).ToList<LowestBid>();

    /*
     If you don't use the .ToList<LowestBid>() and just return the select entity you will
     receive this error when attempting to access the data outside of this using statement:
     Cannot access a disposed object. Object name: 'DataContext accessed after Dispose.'.
     */ 

  }

  catch (Exception)

  {

    return null;

  }

}

 

Tags:

ASP.Net | C# | LINQ to SQL

Email Current HTML Page with ASP.Net

by 24. January 2010 04:57

  /// <summary>
  /// Overridden to handle Confirmation of the order by
  /// capturing the HTTP output and emailing it.
  /// </summary>
  /// <param name="writer"></param>
  protected override void Render(HtmlTextWriter writer)
  {
    // *** Write the HTML into this string builder
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    HtmlTextWriter hWriter = new HtmlTextWriter(sw);
    base.Render(hWriter);
    // *** store to a string
    string PageResult = sb.ToString();
    // *** Write it back to the server
    writer.Write(PageResult);
    // *** Do something with the PageResult here like email it...
  }

Tags: ,

ASP.Net | C#

RegEx: Take a URL and Replace the Page with New Page (isolate page from path and query)

by 14. July 2009 00:35

publicstaticstring ReplaceURLPageName(string URL, string PageNameExtension, string NewPageName)
{
 

// This method takes a URL and replaces the page (with given extension).
 
// Capture the root URL (i.e. everything up to the page
 
// Page is defined by first word with a period in it between slashes
 
string RootURL = "";  

foreach (Match m inRegex.Matches(URL, @"^.*/"))  
{
 
RootURL = m.ToString();
 
}
 

//Strip off everything before the page
 
URL = Regex.Replace(URL, @"^.*/", "");  

//Replace the current page name with new page name (keeping the querystring)
 
URL = RootURL + Regex.Replace(URL, "(.+)." + PageNameExtension, NewPageName);  
System.Diagnostics.Debug.WriteLine(URL);  


return URL;  }

Tags: ,

ASP.Net | C#