Tuesday, December 29, 2009

How To: Get the width and height of the SWF file using C#

Use the below SwfParser class to get the width and height of the SWF file.
This class requires ICSharpCode.SharpZipLib.dll. You can download it from here or ICSharpCode.
  • Use GetDimensions(String filePath) method whenever you want the dimensions of the swf file that resides on your server. Give the complete file path as a parameter.
  • Use GetDimensions(Stream stream) method whenever you want to find the swf file dimensions from the input stream (Ex: Asp.net file upload control's PostedFile.InputStream object.), it can be of any inputStream. Here you no need to save the file on to the server.
These two methods returns Rectangle object, from this object you can get width and height.

Usage:
//Use when the file resides on your server.
try
{
    SwfParser swfParser = new SwfParser();
    Rectangle rectangle = swfParser.GetDimensions(filePath); 
    int width=rectangle.Width;
    int height=rectangle.Height;
       
}
catch (Exception ex)
{
    return "There is a problem with the swf file.";
}

//Use when you want to use file upload control's input stream.(it may be any input stream)
try
{
    SwfParser swfParser = new SwfParser();
    Rectangle rectangle = swfParser.GetDimensions(uploadedfile.PostedFile.InputStream); 
    int width=rectangle.Width;
    int height=rectangle.Height;         
}
catch (Exception ex)
{
    return "There is a problem with the swf file.";
}

Here is the SwfParser class:
using System;
using System.Text;
using System.IO;
using System.Drawing;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;

public class SwfParser
{
    public Rectangle GetDimensions(String filePath)
    {
        using (FileStream stream = File.OpenRead(filePath))
        {
            return GetDimensions(stream);
        }
    }

    public Rectangle GetDimensions(Stream stream)
    {        
        Stream inputStream = null;
        byte[] signature = new byte[8];
        byte[] rect = new byte[8];
        stream.Read(signature, 0, 8);
        if ("CWS" == System.Text.Encoding.ASCII.GetString(signature, 0, 3))
        {
            inputStream = new InflaterInputStream(stream);
        }
        else
        {
            inputStream = stream;
        }

        inputStream.Read(rect, 0, 8);
        int nbits = rect[0] >> 3;
        rect[0] = (byte)(rect[0] & 0x07);
        String bits = ByteArrayToBitString(rect);
        bits = bits.Remove(0, 5);
        int[] dims = new int[4];
        for (int i = 0; i < 4; i++)
        {
            char[] dest = new char[nbits];
            bits.CopyTo(0, dest, 0, bits.Length>nbits ? nbits : bits.Length);
            bits = bits.Remove(0, bits.Length > nbits ? nbits : bits.Length);
            dims[i] = BitStringToInteger(new String(dest)) / 20;
        }

        return new Rectangle(0, 0, dims[1] - dims[0], dims[3] - dims[2]);
    }

    private int BitStringToInteger(String bits)
    {
        int converted = 0;
        for (int i = 0; i < bits.Length; i++)
        {
            converted = (converted << 1) + (bits[i] == '1' ? 1 : 0);
        }
        return converted;
    }

    private String ByteArrayToBitString(byte[] byteArray)
    {
        byte[] newByteArray = new byte[byteArray.Length];
        Array.Copy(byteArray, newByteArray, byteArray.Length);
        String converted = "";
        for (int i = 0; i < newByteArray.Length; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                converted += (newByteArray[i] & 0x80) > 0 ? "1" : "0";
                newByteArray[i] <<= 1;
            }
        }
        return converted;
    }
}

Configuring WCF services to work with both HTTP and HTTPS

1) Write two endpoints for the service, one is for http and another for https.
<services>
    <service behaviorConfiguration="MyServiceBehavior" name="JK.MyService">
      
      <endpoint address="" behaviorConfiguration="WebBehavior" binding="webHttpBinding" bindingConfiguration="webBinding" contract="JK.IMyService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>

      <endpoint address="" behaviorConfiguration="WebBehavior" binding="webHttpBinding" bindingConfiguration="webBindingHTTPS" contract="JK.IMyService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>     
      
    </service>
  </services>
2) Enable both httpGetEnabled="True" httpsGetEnabled="true" in serviceBehaviors.
<behaviors>
    
    <serviceBehaviors>      
      <behavior name="MyServiceBehavior">
        <serviceMetadata httpGetEnabled="True" httpsGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="true" />
      </behavior>      
    </serviceBehaviors>
    
    <endpointBehaviors>
      <behavior name="WebBehavior">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
    
  </behaviors>
3) Write two bindings configurations for http and https. For http give security mode="None" and for https give mode="Transport".
<bindings>
    <webHttpBinding>

      <binding name="webBinding">
        <security mode="None">
          <transport clientCredentialType="None" />
        </security>
      </binding>

      <binding name="webBindingHTTPS">
        <security mode="Transport">
          <transport clientCredentialType="None" />
        </security>
      </binding>

    </webHttpBinding>
  </bindings>
Below are the complete configuration settings in web.config:
<system.serviceModel>
  
  <services>
    <service behaviorConfiguration="MyServiceBehavior" name="JK.MyService">
      
      <endpoint address="" behaviorConfiguration="WebBehavior" binding="webHttpBinding" bindingConfiguration="webBinding" contract="JK.IMyService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>

      <endpoint address="" behaviorConfiguration="WebBehavior" binding="webHttpBinding" bindingConfiguration="webBindingHTTPS" contract="JK.IMyService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>

      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      
    </service>
  </services>
    
  <behaviors>
    
    <serviceBehaviors>      
      <behavior name="MyServiceBehavior">
        <serviceMetadata httpGetEnabled="True" httpsGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="true" />
      </behavior>      
    </serviceBehaviors>
    
    <endpointBehaviors>
      <behavior name="WebBehavior">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
    
  </behaviors>
  
  <bindings>
    <webHttpBinding>

      <binding name="webBinding">
        <security mode="None">
          <transport clientCredentialType="None" />
        </security>
      </binding>

      <binding name="webBindingHTTPS">
        <security mode="Transport">
          <transport clientCredentialType="None" />
        </security>
      </binding>

    </webHttpBinding>
  </bindings>
  
</system.serviceModel>

Sunday, December 20, 2009

Getting the password of the IIS users IUSR_MachineName and IWAM_MachineName


Copy the following code into a .vbs file and run it on the machine you wish to get the account details from.


Dim IIsObject
Set IIsObject = GetObject ("IIS://localhost/w3svc")
WScript.Echo "UserName = " & IIsObject.Get("AnonymousUserName") & vbCrlf & _
"UserPass = " & IIsObject.Get("AnonymousUserPass") & vbCrlf & vbCrlf &_
"WAMUser = " & IIsObject.Get("WAMUserName") & vbCrlf & _
"WAMPass = " & IIsObject.Get("WAMUserPass")
Set IIsObject = Nothing


Friday, December 18, 2009

Sitefinity- Filtering Tags for specific blog in a Tag Cloud

Recently i was working on a sitefinity project. The problem i was facing was, there are 5 blogs in my website and i want to show all the blogs separately on different pages.
When i use the Tags List control on the page, it is showing all the tags from all the blogs.
But my requirement is, i want only Tags related to specific blog.

I managed to come up with a simple solution that requires creating a custom control that inherits from TagsList, implementing a simple property and overriding one method - InitializeControls.

Save this class file into App_Code folder.
Make a entry into web.config file.(in <toolboxcontrols> tag)
<add name="FilteredTags Cloud" section="Tags & Categories" type="Ramp.TagsListFiltered, App_Code" description="Displays Blog related tags" />

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Telerik.Cms.Engine.WebControls.Categories;
using Telerik.Cms.Engine.WebControls.Tags;
using Telerik.Cms.Web.UI;
using System.ComponentModel;
using System.Collections;
using Telerik.Cms.Engine;
using Telerik.Blogs;
using Telerik.Cms;
using System.Web.UI;
using Telerik.Cms.Engine.Data;
using System.Web.UI.WebControls;
using Telerik.Web;


namespace Ramp
{
/// 
/// Summary description for TagsListFiltered
/// 
public class TagsListFiltered : TagsList
{
public TagsListFiltered()
{

}

#region Private contstraints
private Guid[] selectedBlogs = new Guid[] { };
private BlogManager blogManager;
#endregion

public override string LayoutTemplatePath
{
 get
 {
    return "~/Sitefinity/ControlTemplates/Generic_Content/TagsList.ascx";
 }
}

[TypeConverter("Telerik.Blogs.WebControls.SelectedBlogsConverter, Telerik.Blogs")]
[WebEditor("Telerik.Blogs.WebControls.BlogsSelector, Telerik.Blogs")]
public Guid[] SelectedBlogs
{
    get
    {
        return this.selectedBlogs;
    }
    set
    {
        this.selectedBlogs = value;
    }
}

#region Methods

protected override void InitializeControls(Control controlContainer)
{
 IList<ITag> blogTags = new List<ITag>();

 blogManager = new BlogManager("Blogs");
 if (this.selectedBlogs.Length == 0)
 {
    // call the base class we will not change anything. 
    //base.BindCategories();
 }
 else
 {
    IList allBlogs = blogManager.GetBlogs(selectedBlogs);
    foreach (IBlog blog in allBlogs)
    {
        IList blogPosts = blog.Posts;
        foreach (IContent post in blogPosts)
        {
            IList postTags = blogManager.Content.GetTags(post.ID);
            foreach (ITag tag in postTags)
            {
                if (!blogTags.Contains(tag))
                {
                    blogTags.Add(tag);
                }
            }
        }
    }

    if (this.DefaultDisplayMode == DisplayMode.List)
    {
        this.TagsRepeaterList.DataSource = blogTags;
        this.TagsRepeaterList.ItemDataBound += new RepeaterItemEventHandler(this.TagsRepeaterList_ItemDataBound);
        this.TagsRepeaterList.DataBind();
    }
    else
    {
        this.TagsRepeaterCloud.DataSource = blogTags;
        this.TagsRepeaterCloud.ItemDataBound += new RepeaterItemEventHandler(this.TagsRepeaterCloud_ItemDataBound);
        this.TagsRepeaterCloud.DataBind();
    }

    if (this.ControlTitleControl != null)
    {
        this.ControlTitleControl.Text = this.ControlTitle;
    }

    this.TagsRepeaterCloud.Visible = this.DefaultDisplayMode == DisplayMode.Cloud;
    this.TagsRepeaterList.Visible = this.DefaultDisplayMode == DisplayMode.List;
    if (this.DisplayCloudLink != null)
    {
        this.DisplayCloudLink.Enabled = this.DefaultDisplayMode == DisplayMode.List;
        this.DisplayCloudLink.CommandName = "DisplayCloud";
        this.DisplayCloudLink.Command += new CommandEventHandler(this.Button_CommandNew);
    }
    if (this.DisplayListLink != null)
    {
        this.DisplayListLink.Enabled = this.DefaultDisplayMode == DisplayMode.Cloud;
        this.DisplayListLink.CommandName = "DisplayList";
        this.DisplayListLink.Command += new CommandEventHandler(this.Button_CommandNew);
    }
 }
}

private void Button_CommandNew(object sender, CommandEventArgs e)
{
 string commandName = e.CommandName;
 if (commandName != null)
 {
    if (!(commandName == "DisplayCloud"))
    {
        if (!(commandName == "DisplayList"))
        {
            return;
        }
    }
    else
    {
        this.DefaultDisplayMode = DisplayMode.Cloud;
        base.ChildControlsCreated = false;
        return;
    }
    this.DefaultDisplayMode = DisplayMode.List;
    base.ChildControlsCreated = false;
 }
}

private void TagsRepeaterCloud_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
 if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
 {
    int num3;
    ITag dataItem = (ITag)e.Item.DataItem;
    HyperLink link = (HyperLink)e.Item.FindControl("tagLink");
    link.Text = dataItem.TagName;
    link.NavigateUrl = (this.TagKeyType == TagKeyTypes.ID) ? base.ResolveUrl(this.TaggedContentUrl + "?" + this.TagItemKey + "=" + dataItem.ID.ToString()) : base.ResolveUrl(this.TaggedContentUrl + "?" + this.TagItemKey + "=" + dataItem.TagName);
    IUrlService languageService = UrlServices.GetLanguageService();
    if (languageService != null)
    {
        link.NavigateUrl = languageService.ResolveLanguageUrl(link.NavigateUrl);
    }
    float num = Convert.ToSingle(this.Manager.ContentCount(SelectedBlogs));
    float num4 = Convert.ToSingle(dataItem.ContentsTagged) / num;
    if (num4 > 0.83)
    {
        num3 = 1;
    }
    else if (num4 > 0.66)
    {
        num3 = 2;
    }
    else if (num4 > 0.5)
    {
        num3 = 3;
    }
    else if (num4 > 0.33)
    {
        num3 = 4;
    }
    else
    {
        num3 = (num4 > 0.16) ? 5 : 6;
    }
    string str = link.CssClass + num3.ToString();
    link.CssClass = str;
 }
}

private void TagsRepeaterList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
 if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
 {
    ITag dataItem = (ITag)e.Item.DataItem;
    HyperLink link = (HyperLink)e.Item.FindControl("tagLink");
    link.Text = dataItem.TagName;
    link.NavigateUrl = (this.TagKeyType == TagKeyTypes.ID) ? base.ResolveUrl(this.TaggedContentUrl + "?" + this.TagItemKey + "=" + dataItem.ID.ToString()) : base.ResolveUrl(this.TaggedContentUrl + "?" + this.TagItemKey + "=" + dataItem.TagName);
    IUrlService languageService = UrlServices.GetLanguageService();
    if (languageService != null)
    {
        link.NavigateUrl = languageService.ResolveLanguageUrl(link.NavigateUrl);
    }
    ITextControl control = (ITextControl)e.Item.FindControl("taggedContentCount");
    control.Text = dataItem.ContentsTagged.ToString();
 }
}

#endregion
}
}