Wednesday, June 20, 2012

Logging error to text file c#.Net

1. Add new static "ErrorLoging" class to solution and paste the below code in cs file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Diagnostics;

/// <summary>
/// class contain methode for logging WriteToErrorLogFile_Trace(string)
/// </summary>
public  static class ErrorLoging
{
    /// <summary>
    /// log error to path metion in web.config file for key "ErrorFolderPath".
    /// new file will be created for each day
    /// </summary>
    /// <param name="msg">error msg to log.</param>
    /// <param name="ex">exception object, Pass null to just log some msg.</param>
    public static void WriteToErrorLogFile_Trace(string msg,Exception ex)
    {
        try
        {
            if (!System.IO.Directory.Exists(System.Configuration.ConfigurationManager.AppSettings["ErrorFolderPath"] + "\\Errors\\"))
            {
                System.IO.Directory.CreateDirectory(System.Configuration.ConfigurationManager.AppSettings["ErrorFolderPath"] + "\\Errors\\");
            }
            //if (!System.IO.File.Exists(Application.StartupPath + "\\Errors\\" + DateTime.Today.Date.ToString().Replace('/', ' ').Replace(':', ' ')+".txt"))
            //{
            //    System.IO.File.Create(Application.StartupPath + "\\Errors\\" + DateTime.Today.Date.ToString().Replace('/', ' ').Replace(':', ' ') + ".txt");
            //}



            FileStream fs1 = new FileStream(System.Configuration.ConfigurationManager.AppSettings["ErrorFolderPath"] + "\\Errors\\" + DateTime.Today.Year.ToString() + DateTime.Now.ToString("MM") + DateTime.Now.ToString("dd") + ".txt", FileMode.Append, FileAccess.Write);
            StreamWriter s1 = new StreamWriter(fs1);


Friday, May 18, 2012

getting querystring from string

I was having a URL as string
e.g. string videoURL="http://www.youtube.com/watch?v=Rz-Lejndrys";

So now if I wanted to get the value of querstring v. We can get sub-string of videoURL or there is one more method to fetch value of v from above string.

 Uri videoPrevUri = new Uri(videoURL);
 string videoID = HttpUtility.ParseQueryString(videoPrevUri.Query).Get("v");

videoID will return you the value of v

Monday, March 12, 2012

Regular expression for special character in C#

Regex reg = new Regex("[~#%&;*{}\\:<>?/\"|$]+");
 if (reg.IsMatch(TxtBox.Text.Trim()))
{
//Error Msg
}

getting only file name from fileupload control and checking for special character in file name :-JQuery

function ValidateThumbnail() {
//get file name
        var path = $("[id$=fileUploadControl]").val();
        var pos = path.lastIndexOf(path.charAt(path.indexOf(":") + 1));
      
        var f = path.substring(pos + 1);
       //check for special char
        if ((f.indexOf("#", 0) >= 0)
        || (f.indexOf("&", 0) >= 0)
        || (f.indexOf("*", 0) >= 0)
        || (f.indexOf(";", 0) >= 0)
        || (f.indexOf("$", 0) >= 0)
        || (f.indexOf("%", 0) >= 0)
        || (f.indexOf("^", 0) >= 0)
        || (f.indexOf("{", 0) >= 0)
        || (f.indexOf("}", 0) >= 0)
        || (f.indexOf("|", 0) >= 0)
        || (f.indexOf("/", 0) >= 0)
        || (f.indexOf("?", 0) >= 0)
        || (f.indexOf("~", 0) >= 0)
        || (f.indexOf(":", 0) >= 0)
        || (f.indexOf("<", 0) >= 0)
        || (f.indexOf(">", 0) >= 0)
        || (f.indexOf("\"", 0) >= 0)
        ) {
            alert("File: [" + f + "] contains invalid character");
            return false; //will stop button click event here
        }
        return true;
    }

JQuery POP UP during page load /Post back

give call to below fuction on client click

function ShowLoading(e) {
        var div = document.createElement('div');
        var img = document.createElement('img');
        img.src = '/_layouts/Portal/Images/ajax-loader-1.gif';
        div.innerHTML = "Please wait...<br />";
        div.style.cssText = 'position: fixed; top: 30%; left: 40%; z-index: 5000; width: 222px; text-align: center; background: #fff; border: 1px solid #000';
        div.appendChild(img);
        document.body.appendChild(div);
       
    }

TaxonomyWebTaggingControl in UpdatePanel with AJAX

When asyncronuous postback will happen it will not load the TaxonomyWebTaggingControl because DOM gets null.
Use below methode to load TaxonomyWebTaggingControl  after asyn postback.

private string GetReloadJavaScript(TaxonomyWebTaggingControl taxonomyControl)
        {
            String script = String.Empty;
          
            String containerId = SPEncode.ScriptEncode(taxonomyControl.Controls[1].ClientID);
            Type type_TaxonomyWebTaggingControl = typeof(TaxonomyWebTaggingControl);
            MethodInfo mi_getOnloadJavascript = type_TaxonomyWebTaggingControl.GetMethod("getOnloadJavascript", BindingFlags.NonPublic | BindingFlags.Instance);
            String fullScript = (String)mi_getOnloadJavascript.Invoke(taxonomyControl, null);
            int pos = fullScript.IndexOf(String.Format("function {0}_load()", containerId));
            if (pos > -1)
            {
                StringBuilder builder = new StringBuilder();
                builder.Append("var myPrm_" + taxonomyControl.ID + " = Sys.WebForms.PageRequestManager.getInstance();");
                builder.Append("myPrm_" + taxonomyControl.ID + ".add_endRequest(EndRequest_" + taxonomyControl.ID + ");");
                builder.Append("function EndRequest_" + taxonomyControl.ID + "(sender, args)");
                builder.Append("{");
                // we get te first part of the script needed to initialization
                // we start from pos 1, because we don't need the leading '{'
                builder.Append(fullScript.Substring(1, pos - 1));
                builder.Append("Microsoft.SharePoint.Taxonomy.ScriptForWebTaggingUI.onLoad('");
                builder.Append(containerId);
                builder.Append("');");
                builder.Append("}}");
                script = builder.ToString();
            }
            return script;
        }



How to call above methode

String key1 = "TaxonomyWebTaggingAjaxIncludeOnce1";
                if (!this.Page.ClientScript.IsClientScriptBlockRegistered(base.GetType(), key1))
                {
                    this.Page.ClientScript.RegisterClientScriptBlock(base.GetType(), key1, GetReloadJavaScript(taxanomyProjectCategory_taxonomyControl), true);

                }

give multiple call to methode for all taxonomy controls on page.

Friday, January 27, 2012

Remove user from Sharepoint group using powershell


PS C:\Users\ADM> $spWeb = Get-SPWeb http://abc/
PS C:\Users\ADM> $group=$spWeb.SiteGroups["Legal Approvers"]
PS C:\Users\ADM> $group.Users
PS C:\Users\ADM> $theuser = $spWeb.AllUsers.Item("SHAREPOINT\system")
PS C:\Users\ADM> $group.RemoveUser($theuser)
PS C:\Users\ADM> $group.Update()
PS C:\Users\ADM> $group.Users

SharePoint document metadata not updating

I faced a weird issue today, Metadata for document which has lookup column was not updating even after saving the item. There was no erro...