Wednesday 19 November 2014

Get Url Reference - asp.net

Leave a Comment
This is just for reference to get the URL based on HttpRequest Class.

You can call the method below :

Request.ApplicationPath :   /virtual_dir

Request.CurrentExecutionFilePath :  /virtual_dir/webapp/page.aspx

Request.FilePath :  /virtual_dir/webapp/page.aspx

Request.Path :  /virtual_dir/webapp/page.aspx

Request.PhysicalApplicationPath :   d:\Inetpub\wwwroot\virtual_dir\

Request.QueryString :   /virtual_dir/webapp/page.aspx?q=qvalue

Request.Url.AbsolutePath :  /virtual_dir/webapp/page.aspx

Request.Url.AbsoluteUri :   http://localhost:2000/virtual_dir/webapp/page.aspx?q=qvalue

Request.Url.Host :  localhost

Request.Url.Authority : localhost:80

Request.Url.LocalPath : /virtual_dir/webapp/page.aspx

Request.Url.PathAndQuery :  /virtual_dir/webapp/page.aspx?q=qvalue

Request.Url.Port :  80

Request.Url.Query : ?q=qvalue

Request.Url.Scheme :    http

Request.Url.Segments :  /

    virtual_dir/

    webapp/

    page.aspx





By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Wednesday 8 October 2014

Kentico 8.1 - Custom Upload Form Control [Solved to support custom table to store image/binary stream data]

Leave a Comment
Kentico is a powerful CMS engine that allow you to developed portal very fast. But when you have a really big data such as (10,000 above), you may need to think a different way to store the data(Not put all document as a Page Menu Item).

I have heard kentico have test their product for 100K document. But from my experience using shared server, it is cause a lot of painful if you want to expand the node in your page module, and even very slow to load the data.(That is my situation).

So after all, I have decided to developed a "Custom Upload FormControl" to make Custom table support for upload files/media. This implementation is quite tricky because the custom formcontrol just store link to custom table field and it will store the image into media library folder. Look at the flow below :
  1. User/admin upload image using custom formcontrol
  2. Custom formcontrol check folder in media library, if not exist, create media library folder.(Each user will have their own folder so in future if you want to limit the folder size, you can modified the code to check folder file is user have exceed their storage - quite cool ha B-) 
  3. Custom form control will save link to custom table
I will share the code here, and you can test by your self. 
Before That you need to create Media Library name "UserMedia".

Note : This is just example only, the code may have a bug. Use it at your own risk.

ASCX page

<cms:Uploader ID="uploader" runat="server" OnOnDeleteFile="uploader_OnDeleteFile1" OnOnUploadFile="uploader_OnUploadFile1" />

<asp:Button ID="hdnPostback" CssClass="HiddenButton" runat="server" EnableViewState="false" />



Code Behind

using System;
using System.Collections.Generic;

using CMS.Base;
using CMS.DataEngine;
using CMS.DocumentEngine;
using CMS.ExtendedControls;
using CMS.FormControls;
using CMS.FormEngine;
using CMS.Helpers;
using CMS.IO;
using CMS.OnlineForms;
using CMS.SiteProvider;
using CMS.Membership;
using CMS.MediaLibrary;

public partial class CMSFormControls_CustomUploadControl : FormEngineUserControl

{

    #region "Constants"

    private const string FORBIDDEN_EXTENSIONS = ";aspx;ashx;asp;cshtml;vbhtml;";

    #endregion


    #region "Variables"

    private string mValue;
    private UserInfo updateUser;   

    #endregion


    #region "Properties"

    /// <summary>
    /// Gets or sets the enabled state of the control.
    /// </summary>
    public override bool Enabled
    {
        get
        {
            return uploader.Enabled;
        }
        set
        {
            uploader.Enabled = value;
        }
    }



    /// <summary>
    /// GetCurrent User
    /// </summary>
    public UserInfo UpdateUser
    {
        get
        {
            if (updateUser == null)
            {
                updateUser = UserInfoProvider.GetUserInfo(MembershipContext.AuthenticatedUser.UserName);
            }
            return updateUser;
        }
        set
        {
            updateUser = value;
        }
    }


    /// <summary>
    /// Gets or sets form control value.
    /// </summary>
    public override object Value
    {
        get
        {
            if (String.IsNullOrEmpty(mValue) || (mValue == Guid.Empty.ToString()))
            {
                return null;
            }
            return mValue;
        }
        set
        {
            mValue = ValidationHelper.GetString(value, String.Empty);
        }
    }

    #endregion



    #region "Methods"

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (FieldInfo != null)
        {
            uploader.ID = FieldInfo.Name;
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    { 

        if (!RequestHelper.IsPostBack())
        {
            Session["AlreadyDone"] = false;    

        }   

        // Apply styles
        if (!String.IsNullOrEmpty(ControlStyle))
        {
            uploader.Attributes.Add("style", ControlStyle);
            ControlStyle = null;
        }
        if (!String.IsNullOrEmpty(CssClass))
        {
            uploader.CssClass = CssClass;
            CssClass = null;
        }

        // Set image auto resize configuration
        if (FieldInfo != null)
        {
            int uploaderWidth;
            int uploaderHeight;
            int uploaderMaxSideSize;
            ImageHelper.GetAutoResizeDimensions(FieldInfo.Settings, SiteContext.CurrentSiteName, out uploaderWidth, out uploaderHeight, out uploaderMaxSideSize);
            uploader.ResizeToWidth = uploaderWidth;
            uploader.ResizeToHeight = uploaderHeight;
            uploader.ResizeToMaxSideSize = uploaderMaxSideSize;
        }
        CheckFieldEmptiness = false;
    }


    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);    

         // Hide hidden button
        hdnPostback.Style.Add("display", "none");


        // Do no process special actions if there is no form
        if (Form == null)
        {
            return;
        }

        // ItemValue is GUID or file name (GUID + extension) when working with forms
        if (mValue.LastIndexOfCSafe(".") == -1)
        {
             Guid fileGuid = ValidationHelper.GetGuid(Value, Guid.Empty);

             if (fileGuid != Guid.Empty)
             {

             }

             //Response.Write(fileGuid.ToString());
        }
        else
        {

            uploader.CurrentFileName = (Form is BizForm) ? ((BizForm)Form).GetFileNameForUploader(mValue) : FormHelper.GetOriginalFileName(mValue);           

            // Get media library
            MediaLibraryInfo library = MediaLibraryInfoProvider.GetMediaLibraryInfo("UserMedia", SiteContext.CurrentSiteName);
            if (UpdateUser == null)
            {
                UpdateUser = UserInfoProvider.GetUserInfo(MembershipContext.AuthenticatedUser.UserName);

            }
            if (library != null)
            {

                string folderName = "Custom" + String.Join(" ", SqlHelper.GetSafeQueryString(updateUser.UserName).Split(' '));

                string fileName = uploader.CurrentFileName;

                string filePath = "~/" + SiteContext.CurrentSiteName + "/media/" + library.LibraryFolder + "/" + folderName;

                string fullPath = filePath + "/" + fileName;

                uploader.CurrentFileUrl = fullPath;

            }
        }

        if (Form != null)
        {
            // Register post back button for update panel
            if (Form.ShowImageButton && Form.SubmitImageButton.Visible)
            {
                ControlsHelper.RegisterPostbackControl(Form.SubmitImageButton);
            }
            else if (Form.SubmitButton.Visible)
            {
                ControlsHelper.RegisterPostbackControl(Form.SubmitButton);
            }
        }
    }



    /// <summary>
    /// Returns true if user control is valid.
    /// </summary>
    public override bool IsValid()
    {
        // Check allow empty
        if ((FieldInfo != null) && !FieldInfo.AllowEmpty && ((Form == null) || Form.CheckFieldEmptiness))
        {
            if (String.IsNullOrEmpty(uploader.CurrentFileName) && (uploader.PostedFile == null))
            {
                // Error empty
                ValidationError += ResHelper.GetString("BasicForm.ErrorEmptyValue");
                return false;
            }
        }

        // Test if file has allowed file-type
        if ((uploader.PostedFile != null) && (!String.IsNullOrEmpty(uploader.PostedFile.FileName.Trim())))
        {
            string customExtension = ValidationHelper.GetString(GetValue("extensions"), String.Empty);
            string extensions = null;

            if (CMSString.Compare(customExtension, "custom", true) == 0)
            {
                extensions = ValidationHelper.GetString(GetValue("allowed_extensions"), String.Empty);
            }

            string ext = Path.GetExtension(uploader.PostedFile.FileName);
            if (!IsFileTypeAllowed(ext, extensions))
            {

                // Add global allowed file extensions from Settings
                if (extensions == null)
                {
                    extensions += ";" + SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSUploadExtensions");

                }

                extensions = (extensions.TrimStart(';')).TrimEnd(';').ToLowerCSafe();

                // Remove forbidden extensions
                var allowedExtensions = new List<string>(extensions.Split(';'));
                foreach (string extension in FORBIDDEN_EXTENSIONS.Split(';'))
                {
                    if (allowedExtensions.Contains(extension))
                    {
                        allowedExtensions.Remove(extension);
                    }
                }

                ValidationError += string.Format(ResHelper.GetString("BasicForm.ErrorWrongFileType"), ext.TrimStart('.'), string.Join(", ", allowedExtensions));
                return false;
            }

        }

        return true;

    }   


    protected void uploader_OnUploadFile1(object sender, EventArgs e)
    {
        if (!(bool)Session["AlreadyDone"] && IsValid())
        {
            // Get media library

            MediaLibraryInfo library = MediaLibraryInfoProvider.GetMediaLibraryInfo("UserMedia", SiteContext.CurrentSiteName);           

            if (UpdateUser == null)
            {
                UpdateUser = UserInfoProvider.GetUserInfo(MembershipContext.AuthenticatedUser.UserName);
            }

            if (library != null)
            {
                // Prepare the parameters
                string folderName = "Custom" + String.Join(" ", SqlHelper.GetSafeQueryString(updateUser.UserName).Split(' '));
                string fileName = uploader.PostedFile.FileName;              

                string filePath = "~/" + SiteContext.CurrentSiteName + "/media/" + library.LibraryFolder + "/" + folderName;             

                string fullPath = filePath + "/" + fileName; 

                //check directory exist, if not create it
                if (!Directory.Exists(filePath))
                {
                    MediaLibraryInfoProvider.CreateMediaLibraryFolder(SiteContext.CurrentSiteName, library.LibraryID, "Custom" + String.Join(" ", SqlHelper.GetSafeQueryString(updateUser.UserName).Split(' ')), false);
                }

                //save file
                uploader.PostedFile.SaveAs(Server.MapPath(fullPath));

                // Create new media file object
                MediaFileInfo mediaFile = new MediaFileInfo(uploader.PostedFile, library.LibraryID,folderName);

                // Create file info
                FileInfo file = FileInfo.New(Server.MapPath(fullPath));
                if (file != null)
                {
                    // Set the properties
                    mediaFile.FileName = file.Name.Split('.')[0];
                    mediaFile.FileTitle = file.Name.Split('.')[0];
                    mediaFile.FileDescription = "File Description";
                    mediaFile.FilePath = folderName + "/" + file.Name;
                    mediaFile.FileExtension = file.Extension;
                    mediaFile.FileMimeType = uploader.PostedFile.ContentType;
                    mediaFile.FileSiteID = SiteContext.CurrentSiteID;
                    mediaFile.FileLibraryID = library.LibraryID;
                    mediaFile.FileSize = file.Length;

                    // Create the media file
                    MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                    Value = mediaFile.FilePath;
                    File.Delete(Server.MapPath(fullPath));
                    Session["AlreadyDone"] = true;
                }
            }

        }
        else
        {
            Session["AlreadyDone"] = false;
        }
    }



    protected void uploader_OnDeleteFile1(object sender, EventArgs e)
    {
        // Get the media file
        MediaFileInfo deleteFile = MediaFileInfoProvider.GetMediaFileInfo(SiteContext.CurrentSiteName, uploader.CurrentFileUrl.Replace("~/<sitename>/media/UserMedia/", ""), null);

        if (deleteFile != null)
        {
            // Delete the media file
            MediaFileInfoProvider.DeleteMediaFileInfo(deleteFile);
            // Clear CurrentFileName and CurrentFileUrl in uploader
            uploader.Clear();
            mValue = "";        

        }          

    }

 #endregion
}




By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Monday 6 October 2014

Adding Dynamic Control from Code Behind - Dropdown, Listbox, Checkbox etc

Leave a Comment
This tutorial / example show how you can add dynamic control from code behind. This example not only limit to Dropdown, Listbox and Checkbox  controls, but you can use this example for any controls. The only things that you need to understand the process.

Step By Step

  1. Create one new project name DynamicControls
  2. Add One web form or web form using master page if you use default template master page.
  3. Copy paste code below respectively.(Note: im using default masterpage template from VS2010)

ASPX code

    <h3>
        This is Dynamic Control Tutorial
    </h3>

    <asp:Button ID="Button1" runat="server" Text="Add ListBox To Panel"
        onclick="Button1_Click" />
    <br />
    <asp:Button ID="Button2" runat="server" Text="Add Dropdown To Panel"
        onclick="Button2_Click" />
    <br />
    <asp:Button ID="Button3" runat="server" Text="Add CheckBox To Panel"
        onclick="Button3_Click" />
    <br />

    <asp:Panel GroupingText="Dynamic Control Added" ID="PanelToAddDynamicControl" runat="server">
    </asp:Panel>



Code Behind

    /// <summary>
    /// Control Type Enumeration
    /// </summary>
    public enum ControlType
    {
        DropDown, ListBox, Checkbox
    }

    public partial class DynamicControl : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                //clear state if any
                ViewState.Remove("dropdown");
                ViewState.Remove("listbox");
                ViewState.Remove("checkbox");
            }
            else if (Page.IsPostBack)
            {
                //recreate if page is postback, this is because the original page dont have
                //Controls that we added through code behind, hence we need to re create the controls again
                if (ViewState["listbox"] != null)
                {
                    AddControl(ControlType.ListBox);
                }
                if (ViewState["dropdown"] != null)
                {
                    AddControl(ControlType.DropDown);
                }
                if (ViewState["checkbox"] != null)
                {
                    AddControl(ControlType.Checkbox);
                }
            }
        }
        public void AddControl(ControlType C)
        {
            List<ListItem> collectionOfItem = new List<ListItem>();
            for (int i = 0; i < 10; i++)
            {
                ListItem LItems = new ListItem();
                LItems.Text = "Item " + i.ToString();
                LItems.Value = "Item " + i.ToString();
                collectionOfItem.Add(LItems);
            }
            switch (C)
            {
                case ControlType.ListBox:
                    ListBox List = new ListBox();
                    List.ID = "ListBox1";
                    foreach (ListItem li in collectionOfItem)
                    {
                        List.Items.Add(li);
                    }
                    if (!(PanelToAddDynamicControl.FindControl("ListBox1") != null))
                        PanelToAddDynamicControl.Controls.Add(List);
                    break;
                case ControlType.DropDown:
                    DropDownList DropDown = new DropDownList();
                    DropDown.ID = "Dropdownlist1";
                    foreach (ListItem li in collectionOfItem)
                    {
                        DropDown.Items.Add(li);
                    }
                    if (!(PanelToAddDynamicControl.FindControl("Dropdownlist1") != null))
                        PanelToAddDynamicControl.Controls.Add(DropDown);
                    break;
                case ControlType.Checkbox:
                    CheckBoxList Checkbox = new CheckBoxList();
                    Checkbox.ID = "CheckBox1";
                    foreach (ListItem li in collectionOfItem)
                    {
                        Checkbox.Items.Add(li);
                    }
                    if (!(PanelToAddDynamicControl.FindControl("CheckBox1") != null))
                        PanelToAddDynamicControl.Controls.Add(Checkbox);
                    break;
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //Listbox
            AddControl(ControlType.ListBox);
            ViewState["listbox"] = true;
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            //Dropdown
            AddControl(ControlType.DropDown);
            ViewState["dropdown"] = true;
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            //checkbox
            AddControl(ControlType.Checkbox);
            ViewState["checkbox"] = true;
        }
    }


Output Example




By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Thursday 21 August 2014

Await in Catch and Finally

Leave a Comment
This is just a brief note to publicize a coming improvement to the async language support.

With the new compilers, changes to the C# language (e.g., async/await) are easier than they used to be. One improvement that is coming is the use of await in catch and finally blocks. This enables your error-handling/cleanup code to be asynchronous without awkward code mangling.

For example, let’s say that you want to (asynchronously) log an exception in one of your async methods.

The natural way to write this is:

 
try
{
  await OperationThatMayThrowAsync();
}
catch (Exception ex)
{
  await MyLogger.LogAsync(ex);
}


And this natural code works fine in Visual Studio “14”. However, the currently-released Visual Studio 2013 does not support await in a catch, so you would have to keep some kind of “error flag” and move the actual error handling logic outside the catch block:
 


Exception exception = null;
try
{
  await OperationThatMayThrowAsync();
}
catch (Exception ex)
{
  exception = ex;
}
if (exception != null)
  await MyLogger.LogAsync(exception);




This is only a simple example; in real-world code, this can get ugly rather quickly!

By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Wednesday 20 August 2014

HEX to ASCII and ASCII to HEX Class - C#

Leave a Comment
This article shows you how to convert string to hexadecimal and vice versa.

HEX TO ASCII Class

 
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualBasic; // I'm using  this class for Hex Converion
namespace Hex_Converter
{
    public class HexConverter
    {
        public string Data_Hex_Asc(ref string Data)
        {
            string Data1 = "";
            string sData = "";
            while (Data.Length > 0)
            //first take two hex value using substring.
            //then  convert Hex value into ascii.
            //then convert ascii value into character.
            {
                Data1 = System.Convert.ToChar(System.Convert.ToUInt32(Data.Substring(0, 2), 16)).ToString();

                sData = sData + Data1;
                Data = Data.Substring(2, Data.Length - 2);
            }
            return sData;
        }

        public string Data_Asc_Hex(ref string Data)
        {
            //first take each charcter using substring.
            //then  convert character into ascii.
            //then convert ascii value into Hex Format

            string sValue;
            string sHex = "";
            while (Data.Length > 0)
            {
                sValue = Conversion.Hex(Strings.Asc(Data.Substring(0, 1).ToString()));
                Data = Data.Substring(1, Data.Length - 1);
                sHex = sHex + sValue;
            }

            return sHex;
        }
    }
}




By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Message Box Class - Confirm,Error, Warning and Info - C#

Leave a Comment
A C# Snippet for creating Message Box with various type of message (Confirm,Error, Warning and Info).

Message Box Class

 
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace messageBox
{
    public static class MsgBox
    {

        // Displays a Confirm type message box    
        // parameter name="sMsg" is The message you want to display
        public static bool Confirm(string sMsg)
        {
            return Confirm("Confirm :", sMsg);
        }
        public static bool Confirm(string sTitle, string sMsg)
        {
            DialogResult ret = MessageBox.Show(sMsg, sTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            return (ret == DialogResult.Yes);
        }

        //---------------------------------------------------------------------
        // Displays a Error type message box      
        // parameter name="sMsg" is The message you want to display
        public static void Error(string sMsg)
        {
            Error("Error :", sMsg);
        }
        public static void Error(string sTitle, string sMsg)
        {
            MessageBox.Show(sMsg, sTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        //---------------------------------------------------------------------
        // Displays a Warning type message box      
        // parameter name="sMsg" is The message you want to display
        public static void Warning(string sMsg)
        {
            Warning("", sMsg);
        }

        //---------------------------------------------------------------------

        // Displays a Warning type message box       
        // parameter name="sCaption" is  Name of Application or Class or Method
        // parameter name="sMsg" is The message you want to display
        public static void Warning(string sCaption, string sMsg)
        {
            if (sCaption.Length == 0)
                sCaption = "Warning";
            MessageBox.Show(sMsg, sCaption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        //---------------------------------------------------------------------
        // Displays a Information type message box       
        // parameter name="sMsg" is The message you want to display
        public static void Info(string sMsg)
        {
            Info("", sMsg);
        }

        //---------------------------------------------------------------------
        // Displays a Information type message box      
        // parameter name="sCaption" is Name of Application or Class or Method
        // parameter name="sMsg" is The message you want to display
        public static void Info(string sCaption, string sMsg)
        {
            if (sCaption.Length == 0)
                sCaption = "Information";
            MessageBox.Show(sMsg, sCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Convert Hex / Css String color to .NET Colour (RGB)

Leave a Comment
Have you facing problem to convert "#CCCCCC" to .NET Colour.?

Here is a solution to convert the CSS / Hex String to .NET Colour (RGB).

Conversion Class

 
using System;
using System.Collections.Generic;
using System.Text;
using System;
using System.Drawing;
using System.Text.RegularExpressions;

namespace Convert_Hex_String_to.NET_Color
{

    public class ConversionClass
    {       

        /// <summary>
        /// Convert a hex string to a .NET Color object.
        /// </summary>
        /// <param name="hexColor">a hex string: "FFFFFF", "#000000"</param>
        public static Color HexStringToColor(string hexColor)
        {
            string hc = ExtractHexDigits(hexColor);
            if (hc.Length != 6)
            {
                // you can choose whether to throw an exception
                //throw new ArgumentException("hexColor is not exactly 6 digits.");
                return Color.Empty;
            }
            string r = hc.Substring(0, 2);
            string g = hc.Substring(2, 2);
            string b = hc.Substring(4, 2);
            Color color = Color.Empty;
            try
            {
                int ri
                   = Int32.Parse(r, System.Globalization.NumberStyles.HexNumber);
                int gi
                   = Int32.Parse(g, System.Globalization.NumberStyles.HexNumber);
                int bi
                   = Int32.Parse(b, System.Globalization.NumberStyles.HexNumber);
                color = Color.FromArgb(ri, gi, bi);
            }
            catch
            {
                // you can choose whether to throw an exception
                //throw new ArgumentException("Conversion failed.");
                return Color.Empty;
            }
            return color;
        }

        /// <summary>
        /// Extract only the hex digits from a string.
        /// </summary>
        public static string ExtractHexDigits(string input)
        {
            // remove any characters that are not digits (like #)
            Regex isHexDigit
               = new Regex("[abcdefABCDEF\\d]+", RegexOptions.Compiled);
            string newnum = "";
            foreach (char c in input)
            {
                if (isHexDigit.IsMatch(c.ToString()))
                    newnum += c.ToString();
            }
            return newnum;
        }

    }  

}


MessageBox Class

 
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace messageBox
{
    public static class MsgBox
    {
        // Displays a Confirm type message box
        // parameter name="sMsg" is The message you want to display
        public static bool Confirm(string sMsg)
        {
            return Confirm("Confirm :", sMsg);
        }
        public static bool Confirm(string sTitle, string sMsg)
        {
            DialogResult ret = MessageBox.Show(sMsg, sTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            return (ret == DialogResult.Yes);
        }

        //---------------------------------------------------------------------
        // Displays a Error type message box      
        // parameter name="sMsg" is The message you want to display
        public static void Error(string sMsg)
        {
            Error("Error :", sMsg);
        }
        public static void Error(string sTitle, string sMsg)
        {
            MessageBox.Show(sMsg, sTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        //---------------------------------------------------------------------
        // Displays a Warning type message box. parameter name="sMsg" is The message you want to display
        public static void Warning(string sMsg)
        {
            Warning("", sMsg);
        }

        //---------------------------------------------------------------------
        // Displays a Warning type message box       
        // parameter name="sCaption" is  Name of Application or Class or Method
        // parameter name="sMsg" is The message you want to display
        public static void Warning(string sCaption, string sMsg)
        {
            if (sCaption.Length == 0)
                sCaption = "Warning";
            MessageBox.Show(sMsg, sCaption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        //---------------------------------------------------------------------
        // Displays a Information type message box    
        // parameter name="sMsg" is The message you want to display
        public static void Info(string sMsg)
        {
            Info("", sMsg);
        }

        //---------------------------------------------------------------------
        // Displays a Information type message box       
        // parameter name="sCaption" is Name of Application or Class or Method
        // parameter name="sMsg" is The message you want to display
        public static void Info(string sCaption, string sMsg)
        {
            if (sCaption.Length == 0)
                sCaption = "Information";
            MessageBox.Show(sMsg, sCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

    }
}


Program Code Behind

 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using messageBox;

namespace Convert_Hex_String_to.NET_Color
{
    public partial class Form1 : Form
    {
        private string msAppName = "Convert CSS String color to .Net Color Class"; // Program Name

        public Form1()
        {
            InitializeComponent();     
        }

        public void TestHexStringToColor(string hexColor)
        {
            // invent some hex colors
            string[] h = new string[1];
            h[0] = hexColor;

            // convert the hex values to colors
            Color[] colors = new Color[4];
            colors[0] = ConversionClass.HexStringToColor(h[0]);

            // print the results
            Result.Text = "";
            for (int i = 0; i < h.Length; i++)
            {
                Result.Text += "\n" + h[i] + " =  "

                   + colors[i].Name + ", Red=" + colors[i].R.ToString()
                   + ", Green=" + colors[i].G.ToString()
                   + ", Blue=" + colors[i].B.ToString();                 

            }

        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MsgBox.Info("Thank You");
            this.Close();
        }

        private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            MsgBox.Info("Created By Mohd Zulkamal. - www.developersnote.com");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string hexColor = textBox1.Text.ToString();
            if (hexColor == "")
            {
                MsgBox.Info("Input was nothing");
                return;
            }
            else if (hexColor.Substring(0, 1) != "#")
            {
                MsgBox.Info("First Character must be \"#\"");
                return;
            }
            else
            {
                try
                {
                    TestHexStringToColor(textBox1.Text.ToString());
                }
                catch (Exception ex)
                {
                    MsgBox.Error(ex.Message.ToString());
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = this.msAppName;
        }
    }
}

Output



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Saturday 16 August 2014

Register winform app HotKeys - C#

Leave a Comment
Hotkey is a very useful shortcut for complex application. Sometimes we build application with much feature include in it hence will result of bad experience of end user because the feature dont have the shortcut keys.

Here is a sample to add shortcut keys or hotkeys for winform app in C# code.

GlobalHotkeys.cs

 
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;


namespace Hotkeys
{
    public class GlobalHotkey
    {
        private int modifier;
        private int key;
        private IntPtr hWnd;
        private int id;


        public GlobalHotkey(int modifier, Keys key, Form form)
        {
            this.modifier = modifier;
            this.key = (int)key;
            this.hWnd = form.Handle;
            id = this.GetHashCode();
        }

        public bool Register()
        {
            return RegisterHotKey(hWnd, id, modifier, key);
        }

        public bool Unregiser()
        {
            return UnregisterHotKey(hWnd, id);
        }

        public override int GetHashCode()
        {
            return modifier ^ key ^ hWnd.ToInt32();
        }

        [DllImport("user32.dll")]

        private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);

        [DllImport("user32.dll")]

        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    }

}


CodeBehind WinForm 

 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Hotkeys;

namespace HotkeyWin
{
    public partial class Form1 : Form
    {
        private Hotkeys.GlobalHotkey ghk;
        public Form1()
        {
            InitializeComponent();
            ghk = new Hotkeys.GlobalHotkey(Constants.ALT + Constants.SHIFT, Keys.O, this);
        }

        private void HandleHotkey()
        {
            WriteLine("Hotkey pressed!");
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == Hotkeys.Constants.WM_HOTKEY_MSG_ID)
                HandleHotkey();
            base.WndProc(ref m);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            WriteLine("Trying to register SHIFT+ALT+O");
            if (ghk.Register())
                WriteLine("Hotkey registered.");
            else
                WriteLine("Hotkey failed to register");
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!ghk.Unregiser())
                MessageBox.Show("Hotkey failed to unregister!");
        }

        private void WriteLine(string text)
        {
            textBox1.Text += text + Environment.NewLine;
        }
    }
}

Output



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Monday 4 August 2014

Get each table size in mssql database

Leave a Comment
This is the snippet to get each table size in the schema/catalogue database.

MSSQL Code

  
SELECT

    t.NAME AS TableName,

    s.Name AS SchemaName,

    p.rows AS RowCounts,

    SUM(a.total_pages) * 8 AS TotalSpaceKB,

    SUM(a.used_pages) * 8 AS UsedSpaceKB,

    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB

FROM

    sys.tables t

INNER JOIN     

    sys.indexes i ON t.OBJECT_ID = i.object_id

INNER JOIN

    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id

INNER JOIN

    sys.allocation_units a ON p.partition_id = a.container_id

LEFT OUTER JOIN

    sys.schemas s ON t.schema_id = s.schema_id

WHERE

    t.NAME NOT LIKE 'dt%'

    AND t.is_ms_shipped = 0

    AND i.OBJECT_ID > 255

GROUP BY

    t.Name, s.Name, p.Rows

ORDER BY

    t.Name


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Wednesday 30 July 2014

How to "PUT" and "GET" queue item IBM WebSphere Queue - C#

Leave a Comment
This is example C# code how to insert value into IBM WebSphere  Queue, and Get The Queue value back.
You can use Queue to store some information to processed later without involve database. You can read more about IBM WebSphere queue in here

Put Message C# Code

            MQQueueManager queueManager;
            MQQueue queue;
            MQMessage queueMessage;
            MQPutMessageOptions queuePutMessageOptions;
            MQGetMessageOptions queueGetMessageOptions;


            string ChannelInfo;
            string channelName;
            string transportType;
            string connectionName;

            //get channel info
            char[] separator = { '/' };
            string[] ChannelParams;

            ChannelInfo = "CHANNEL3/TCP/172.19.37.2";
            ChannelParams = ChannelInfo.Split(separator);
            channelName = ChannelParams[0];
            transportType = ChannelParams[1];
            connectionName = ChannelParams[2];

            //get queue manager
            string queueManagerName = "QMGR3";
            string queueName = "TESTQ";

            queueManager = new MQQueueManager(queueManagerName, channelName, connectionName);
            queue = queueManager.AccessQueue(queueName, MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING);
            queueMessage = new MQMessage();
            queueMessage.WriteString("TEST");
            queueMessage.Format = MQC.MQFMT_STRING;
            queuePutMessageOptions = new MQPutMessageOptions();

            //putting the message into the queue
            queue.Put(queueMessage, queuePutMessageOptions);
            queue.Close();
            MessageBox.Show("Successfully put data into queue");



Get Message C# Code

            MQQueueManager queueManager;
            MQQueue queue;
            MQMessage queueMessage;
            MQPutMessageOptions queuePutMessageOptions;
            MQGetMessageOptions queueGetMessageOptions;

            string ChannelInfo;
            string channelName;
            string transportType;
            string connectionName;

            //get channel info
            char[] separator = { '/' };
            string[] ChannelParams;
            ChannelInfo = "CHANNEL3/TCP/172.19.37.2";

            ChannelParams = ChannelInfo.Split(separator);
            channelName = ChannelParams[0];
            transportType = ChannelParams[1];
            connectionName = ChannelParams[2];

            //get queue manager
            string queueManagerName = "QMGR3";
            string queueName = "TESTQ";

            queueManager = new MQQueueManager(queueManagerName, channelName, connectionName);
            queue = queueManager.AccessQueue(queueName, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING);
            string str_rtn = string.Empty;

            while (true)
            {
                try
                {
                    queueMessage = new MQMessage();
                    queueMessage.Format = MQC.MQFMT_STRING;

                    queueGetMessageOptions = new MQGetMessageOptions();
                    queue.Get(queueMessage, queueGetMessageOptions);
                    str_rtn = queueMessage.ReadString(queueMessage.MessageLength);

                    MessageBox.Show(str_rtn);
                    break;

                }
                catch (MQException MQExp)
                {
                    str_rtn = "MQQueue::Get ended with " + MQExp.Message;
                    MessageBox.Show(str_rtn);
                    return;                  

                }
            }
            queue.Close();


Note : You need to include library IBM.WMQ . ( using IBM.WMQ; )


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

How to get user name of logon windows user.

Leave a Comment
This Code shows how to get user name of log on windows user.

Here is the code :

C# Code 

string a;
a = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString(); 
MessageBox.Show(a.ToString());




By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Friday 4 July 2014

How to specify WhereCondition in Transformation - Nested Control - kentico 8, 7, 6

Leave a Comment
Before this i wonder how to pass some where condition in transformation repeater. So i ask the kentico guys and he give me a solution which i think i can share to the others.

So in your transformation you can specify the <script runat="server"></script> element. This is where you can pass the where condition.

Let see the example :

Transformation Code


<cms:queryrepeater id="repItems" ... DelayedLoading="true" ... />

<script runat="server">
protected void Page_PreRender(object sender, EventArgs e)
{
queryrepeater.WhereCondition= "NodeAliasPath LIKE '"+(string)Eval("NodeAliasPath")+"'";
queryrepeater.ReloadData(true);
}
</script>

Note : queryrepeater dont have DelayedLoading properties, use DataBindByDefault="false" instead.



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Update Panel - Handle async partial-page state with client script

Leave a Comment
This is a sample script you can put at the master page. So that you dont need to have updatepanel progress every time you add the update panel in you aspx page.

Script 

<div id="pageUpdating"></div>

    <script type="text/javascript">
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
        function BeginRequestHandler(sender, args) {
            //page is begin request, you can put code to lock screen etc.  
            writePageLoading();

        }
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler)
        function endRequestHandler(sender, args) {
            //page load successfully , end request  
            RemoveLoading();
            if (args.get_error() != undefined && args.get_error().httpStatusCode == '500') {
                //if have error
                var errorMessage = args.get_error().message;
                alert(errorMessage + " . " + errorMessageAdditional);
            }
        }

        Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler)
        function pageLoadingHandler(sender, args) {
            //page updating..
            writePageUpdating();
        }

        Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler)
        function pageLoadedHandler(sender, args) {
            //page loaded
            RemoveLoading();
        }

        //method to write loading indicator
        function writePageLoading() {
            var divPageUpdating = document.getElementById('pageUpdating');
            divPageUpdating.innerHTML = "<div id=\"loading\" style=\"position: absolute; top: 46%; left: 40%; width: 200px; z-index: 100000;\" class=\"PopupBackground\"><center><br /> <img src=\"images/loading.gif\" alt=\"page is updating\" /><br /><br/>Please Wait While Processing Your Request...</center></div>";

        }

        //method to remove any updating / loading indicator
        function RemoveLoading() {
            var divPageUpdating = document.getElementById('pageUpdating');
            divPageUpdating.innerHTML = "";
        }

        //method to write updating indicator
        function writePageUpdating() {
            var divPageUpdating = document.getElementById('pageUpdating');
            divPageUpdating.innerHTML = "<div id=\"loading\" style=\"position: absolute; top: 46%; left: 40%; width: 200px; z-index: 100000;\" class=\"PopupBackground\"><center><br /> <img src=\"images/loading.gif\" alt=\"page is updating\" /><br /><br/>Please Wait While System Updating Your Page...</center></div>";
        }
    </script>


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Monday 23 June 2014

Javascript Clock example

Leave a Comment
This example show how to insert clock on the website which is not static clock, but like a digital clock.

Script for Creating Clock

 <script type="text/javascript">
        function updateClock() {
            var currentTime = new Date();
            var currentHours = currentTime.getHours();
            var currentMinutes = currentTime.getMinutes();
            var currentSeconds = currentTime.getSeconds();

            // Pad the minutes and seconds with leading zeros, if required
            currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
            currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;

            // Choose either "AM" or "PM" as appropriate
            var timeOfDay = (currentHours < 12) ? "AM" : "PM";
            // Convert the hours component to 12-hour format if needed
            currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;
            // Convert an hours component of "0" to "12"
            currentHours = (currentHours == 0) ? 12 : currentHours;
            // Compose the string for display
            var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
            // Update the time display
            document.getElementById("clock").firstChild.nodeValue = currentTimeString;
            //return currentTimeString;
        }
    </script>


Call the clock on body load

<body onload="updateClock(); setInterval('updateClock()', 1000 );">


Div element for clock

   <div id="clock" style="font-size:larger; font-family:Verdana;">
    </div>


Output


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Tuesday 3 June 2014

Who is connected to database - Sample Application C#

Leave a Comment
This is a sample application just to show who is currently connected into database MSSQL. The application actually just execute MSSQL command "sp_who" and show the data into datagrid.

Below is a screen shoot of the sample application.



Code Behind View Who Is Connected Form 


        public Form1()
        {
            InitializeComponent();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string ipaddress = textBox1.Text;
            string username = textBox2.Text;
            string password = textBox3.Text;
            string dbNAme = textBox4.Text;
            ViewUserActive form = new ViewUserActive();
            form.popupInformation(ipaddress, username, password, dbNAme);       
        }
        private void Form1_Load(object sender, EventArgs e)
        {         
        }

Code Behind ViewUserActive Form


        string ipaddress;
        public string Ipaddress
        {
            get { return ipaddress; }
            set { ipaddress = value; }
        }
        string username;
        public string Username
        {
            get { return username; }
            set { username = value; }
        }
        string password;
        public string Password
        {
            get { return password; }
            set { password = value; }
        }
        string dbNAme;
        public string DbNAme
        {
            get { return dbNAme; }
            set { dbNAme = value; }
        }
        public ViewUserActive()
        {
            InitializeComponent();
        }
        public void popupInformation(string ipadd, string usrName, string pass, string databaseName)
        {
            ViewUserActive form = new ViewUserActive();
            form.Ipaddress = ipadd;
            form.Username = usrName;
            form.Password = pass;
            form.DbNAme = databaseName;
            form.ShowDialog();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void ViewUserActive_Load(object sender, EventArgs e)
        {
            string strConnection = "Data Source=" + Ipaddress + ";Initial Catalog=" + DbNAme + ";Persist Security Info=True;User ID=" + Username + ";Password=" + Password;
            SqlConnection dbConn = new SqlConnection(strConnection);
            SqlCommand dbComm;
            SqlDataReader dbReader;

            DataTable table = new DataTable();
            table.Columns.Add("SPID", typeof(string));
            table.Columns.Add("ECID", typeof(string));
            table.Columns.Add("STATUS", typeof(string));
            table.Columns.Add("LOGINNAME", typeof(string));
            table.Columns.Add("HOSTNAME", typeof(string));
            table.Columns.Add("BLK", typeof(string));
            table.Columns.Add("DBNAME", typeof(string));
            table.Columns.Add("CMD", typeof(string));
            table.Columns.Add("REQUESTID", typeof(string));

            DataTable _temp = new DataTable();
            string strsql = "sp_who";
            dbComm = new SqlCommand(strsql, dbConn);
            dbConn.Open();
            dbReader = dbComm.ExecuteReader();
            if (dbReader.HasRows)
            {
                while (dbReader.Read())
                {
                    string dbName = dbReader["dbname"].ToString();
                    if (dbName.Trim().ToUpper() == DbNAme.Trim().ToUpper())
                    {
                        DataRow row = table.NewRow();
                        row["SPID"] = dbReader["spid"].ToString();
                        row["ECID"] = dbReader["ecid"].ToString();
                        row["STATUS"] = dbReader["status"].ToString();
                        row["LOGINNAME"] = dbReader["loginame"].ToString();
                        row["HOSTNAME"] = dbReader["hostname"].ToString();
                        row["BLK"] = dbReader["blk"].ToString();
                        row["DBNAME"] = dbName;
                        row["CMD"] = dbReader["cmd"].ToString();
                        row["REQUESTID"] = dbReader["request_id"].ToString();
                        table.Rows.Add(row);
                    }
                }
            }

            dbReader.Close();
            dbConn.Close();
            dataGridView1.DataSource = table;
        }



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Kentico 7 - Get Specific document information

Leave a Comment
This post will show how to get specific document information using Transformation In Kentico 7.

Note : i have tested this method in kentico 7 only, donno if the other version will work.

You can refer this link to create new transformation method

Example :

You can use this method in your transformation let say you create new repeater and want to show the parent name of the binding document type data. In this scenario, the document type store under different parent node.

       public string getDocumentInfo(string documentID, string parentProperties)
        {
            TreeProvider tree = new CMS.DocumentEngine.TreeProvider(CMSContext.CurrentUser);
            TreeNode Node = DocumentHelper.GetDocument(Convert.ToInt16(documentID), tree);

            if (Node != null)
            {
                switch (parentProperties)
                {
                    case "NodeID": return Node.NodeID.ToString();
                    case "NodeAliasPath": return Node.NodeAliasPath;
                    case "NodeName": return Node.NodeName;
                    case "NodeAlias": return Node.NodeAlias;
                    case "NodeClassName": return Node.NodeClassName;
                    case "NodeParentID": return Node.NodeParentID.ToString();
                    case "NodeLevel": return Node.NodeLevel.ToString();
                    default: return string.Empty;
                }
            }
            else
            {
                return "Current UserInfo :" + CMSContext.CurrentUser + " Node is null";
            }
        }


How to use

getDocumentInfo(Eval("NodeParentID").ToString(),"NodeName")


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Wednesday 14 May 2014

[SOLVED]Login failed for user ''. (Microsoft SQL Server, Error: 18456)

Leave a Comment
If you want to try to connect to database using sql authentication and the result is failed due to error code "18456" , here are the solution that you might want to try. I already solved the issue (in my case the problem because of the database did not set to allow sql connection to pass. So the solution is to enable the SQL Server authentication.

Enable SQL Server Authentication 

  1. Login to the SQL Server using windows authentication.
  2. Right click on the SQL Server node >> properties.
  3. Go to Security tab.
  4. Under SQL Authentication choose SQL Server and Windows Authentication mode.
  5. Click Ok Button.
  6. Go to Services . Control Panel >> Administrative tools >> Services >> Find SQLServer instance.
  7. Restart SQL Server instance.
  8. Try to login again using your login information.
  9. Done.


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Wednesday 7 May 2014

[SOLVED]Windows Phone 8 - Duplicate Files

Leave a Comment
Windows Phone users around the world have reported that their photos, videos or music automatically create multiple copies of themselves. When you delete a single copy, the rest of them don’t open. There have been ongoing discussions spanning across multiple Windows forums pertaining to the issue, but a real solution hasn’t been found yet.

This bug was probably introduced after GDR 2 update for Windows Phone and usually affects devices with external SD Card support. Some users have suggested that it might be because of the syncing method used (Windows Phone 8 currently uses 4 different ways to import content into the phone: The Windows Phone Modern App, the Windows Phone app for Desktop, using Windows Media Player to sync its contents, or using File Explorer to import items via drag and drop or by copying files). But switching to a different method of syncing doesn’t seem to work for everyone.

Also, re-syncing usually involves emptying the entire media library on the phone, formatting the SD Card and then, and then recopying the music, videos and photos back to the card over again. And even then, you’re not sure the duplication won’t happen again. It’s a lot of time consuming re-work for something that doesn’t even offer a guaranteed fix to the problem.

Well, we have tried out several ways to eliminate duplicates from the Windows Phone library without having to delete an entire media collection. And after a few failed attempts, one of them was successful. It has worked for us and we’re quite certain that it’ll work for you too.

Why does Windows Phone create duplicate media files?

Only the folks over at Microsoft may be able to answer that. We can only make a guess that it occurs when you try to copy / sync an item which is already present on the phone. The phone’s media library is probably maintained by a file, which keeps a tab of all the music, videos and photos present on your SD Card. It would also keep a record of metadata, like song artist, album and so on. In other words, this library file links the information you see on your phone (for example, in the Music + Videos hub) to the files on your SD Card. The file also makes it possible to browse through your media collection without an actual file manager.

When this file gets corrupted, it creates multiple attributes for the same file. So, when you delete a particular copy on your phone, it deletes the actual file present on the SD Card. Now, all the other references to the same file still exist, but the file has been deleted. This might be the reason why the other copies fail to open a file when one copy has been deleted.

SOLUTION

Even though you see multiple copies of media on your phone, Windows Phone does not create multiple copies of files on your Windows Phone. The problem thus lies in a corrupted library file. Unfortunately, there is no way to edit or replace this file. Here, we’ll rather try and let Windows Phone recreate the library from scratch, and this time, without the duplicates.

Note: If you have upgraded to Windows Phone 8.1 and have apps installed on the SD card, the following steps might corrupt these apps. So, make sure you move all your apps to phone memory before proceeding any further. Go to Settings >> Storage Sense >> Tap on SD card >> apps+games. Tap on the selection button at the bottom and check “select all”. Finally, tap on the move button to transfer the apps to phone memory. After successfully completing all the steps, you can transfer the apps back to the SD card if you want to.

Here’s what you should do:

  1. Remove the SD Card from your phone and access it on your computer through a suitable card reader. Once you plug in the card, you should notice only single copies of media files.
  2. Open File Explorer and enable view for hidden files on your computer (Open Folder and Search options >> View tab >> Select Show Hidden files, folders and drives).
  3. Other than media folders (like Music, Videos, etc.), you should see two additional folders labeled WPSystem and System Volume Information on the SD Card. Delete the WPSystem folder. System Volume Information folder can’t be deleted directly on Windows. For deleting it, you need to run a few commands in an elevated (Admin) Command Prompt.Update:  Some of our readers have pointed out that the WPSystem and System Volume Information folders remain hidden even after enabling the “Show Hidden files, folders and drives” option. It appears that you also have to uncheck another option in order to view these folders. Go to Folder and Search options >> View tab >> Uncheck “Hide protected operating system files” option >> Click OK. You will now be able to see both folders in File Explorer.
  4. Note the drive letter assigned to your SD Card.
  5. Go to Start and type “CMD” in the Search box.
  6. Right click on the result (Command Prompt) and choose “Run as Administrator”. Now, execute the following commands one after the other, assuming H is the drive letter assigned to the SD Card:
    - H:
    - attrib -s -h /S /D
    - attrib -r /S /D
    - rd "System Volume Information" /S
    - And enter Y to confirm the delete operation.(Ignore message if the error cannot fine "System Volume Information - because that folder not exist, the action only if you sdcard have System volume information folder)
  7. Now, turn on your Windows Phone and connect it to the computer (without the SD Card).
  8. Navigate to your Phone storage and ensure that there are no references of files from the SD Card. Usually you’d save your photos, videos and music on the SD Card, so the Phone Storage should not display any media file. You may transfer everything from phone storage to sdcard
  9. Disconnect both the phone and SD Card from your computer and insert the card back onto the phone.
  10. Power on the Windows Phone and let it rebuild its library file.


Hopefully, by following these steps, you would have successfully got rid of duplicate file copies. If you found this article helpful, don’t forget to share it with other fellow Windows Phone users.


NOTE : 

  1. Do not copy Camera Roll Folder in memory card using card reader. After rebuild done, then you may copy the Camera Roll Files in the folder using their File Explorer. 
  2. This method sometime work sometime didnt, you need to try and retry again because in my experience the duplicate sometime exist in Folder A, but not Exist in Folder B. If this is the situation(after step 10 done). Then you can plug in USB cable and find the duplicate folder. Delete the folder(Make Sure the Folder cannot see in the photos app in your phone after delete it- If you still see the photo and folder after delete using File explorer, you may wait for a while until the folder dissappear or unplug the cable usb). Then add the folder again using the File Explorer
  3. Make Sure you put files in the correct folder which music files in the Music Folder, image files in Picture Folder and video files in the Videos Folder
  4. This solution works for my Nokia Lumia 1520 . It is soo embarrassing to Microsoft which is cannot build the OS which cannot verify the files before listing the files to end user. Boooo... Windows smart phone is not the "SMART" phone, but "DIFFICULT" phone. End.


Original Article : http://7labs.heypub.com/mobile/fix-media-library-duplicates-windows-phone-8.html


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
Read More...

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.