Wednesday, 19 March 2014

Refresh Parent Page and closing the Rad window using Customize Url

We may have scenarios like closing the rad window where the rad window will call different page and refresh the parent page with customized url after task is finished in rad window
In that case

First Add the following java script to the page where Rad window is navigated

 <script type="text/javascript">
        // Get Rad Window
        function getRadWindow() {
            var oWindow = null;
            if (window.radWindow)
                oWindow = window.radWindow;
            else if (window.frameElement.radWindow)
                oWindow = window.frameElement.radWindow;
            return oWindow;
        }

        // Redirect page to url
        function redirectParentPage(url) {
            getRadWindow().BrowserWindow.document.location.href = url;
        }
    </script>

Next in that page code behind file  Add the following logic to respect event handler

//Customized Url
 string url = "";
 Page.ClientScript.RegisterClientScriptBlock(GetType(), "CloseScript", "redirectParentPage('" + url + "')", true);

This is will redirect to the parent page and refresh it.

Thursday, 2 January 2014

Export Access Reports to excel which are having sub reports,group totals to excel with RTF file using VBA



Iam explaining how to export complex access report which are having sub reports,group totals  to excel with rtf file using automation Process and Vba


First we will  export our report to rtf file using docmd method like as below


DoCmd.OutputTo acOutputReport, "ReportName", acFormatRTF, "ReportPath", False


Next we will create  an excel object and copy all the word content to this file and save  it using following code

Please add Microsoft word,excel as references (click on tools and option refernces to get list of available refernces)

Sub DemoOfPasteToExcelFromWord()

    Dim oWord As Object, oDoc As Object
    Set oWord = CreateObject("Word.Application")
 
    '~~> Open the Attachement
    Set oDoc = oWord.Documents.Open(FileName:="Path of rtf file", ConfirmConversions:=False, _
        ReadOnly:=False, AddToRecentFiles:=False, PasswordDocument:="", _
        PasswordTemplate:="", Revert:=False, WritePasswordDocument:="", _
        WritePasswordTemplate:="", Format:=0, XMLTransform:="", _
        Encoding:=1200)

    '~~> Get the comeplete text and copy it

    oDoc.Range.Copy
    oDoc.Close

   ' create excel workbook
   Dim oExcelApp As Object
   Dim oExcelWrkBook As Object

   Set oExcelApp = CreateObject("Excel.Application")
   Set oExcelWrkBook = oExcelApp.Workbooks.Add
   oExcelWrkBook.Application.Visible = False
   oExcelWrkBook.Worksheets(1).Range("A1").Select
   oExcelWrkBook.Worksheets(1).Paste
   oExcelWrkBook.SaveAs ("Path where we want to save file with extension like xls or xlsx")
   oExcelWrkBook.Close
 
   'Clean objects
   Set oDoc = Nothing
   Set oExcelApp = Nothing
   Set oWord = Nothing
   Set oExcelWrkBook = Nothing


End Sub

Friday, 24 August 2012

Pass Dynamic Parameter to Java script from asp.net code behind page

How to Pass Parameter to javascript from asp.net code behind page


In Your design Page
do like
 <script type="text/javascript">
       

          var Id = '<%= ID %>';
         
          //logic goes here

    </script>



In Your code behind page

  public string ID
        { get { return Parametervalue} }

//Pass Parameter value here

string Parametervalue="";

Thursday, 2 August 2012

Post To FaceBook Page in asp.net


First Register Your Application and  get Client Id

Then after user authenticate Your App you will get Access Token

User authentication Process

First place Two buttons For Authorization  on web form
In authorization button click Event Write the following code
We set Offline access ,Publish stream Permission,manage Pages Permission   of users to post on page
protected void Authorization_Click(object sender, EventArgs e)
        {
         
       //     Your Website Url which needs to Redirected
              string callbackUrl = "xxxxxxx";

       //Client Id Which u Got when you Register You Application
       string   FacebookClientId="xxxx";
            Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri{1}&scope=offline_access,publish_stream,read_stream,publish_actions,manage_pages",FacebookClientId, callbackUrl));
         

        }
After user Authorizes  U will Receive Oauth code.use the below  URL to get  Access token For that user

           https://graph.facebook.com/oauth/access_token?
     client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
     client_secret=YOUR_APP_SECRET&code=The code U got from face book after Redirecting


This will Return User Access token save it For Further use


Then After We need to  get Pages information of user

Use Below Method to get Page tokens and IDs



             public void getpageTokens()

            {
                // User Access Token  we got After authorization

               string UserAccesstoken="xxxxxx";
                string url = string.format("https://graph.facebook.com/me/accounts?access_token={0}",UserAccesstoken);

                webRequest.ContentType = "application/x-www-form-urlencoded";

                webRequest.Method = "Get";

           
                 var webResponse = webRequest.GetResponse();

                 StreamReader sr = null;

                   
                 sr = new StreamReader(webResponse.GetResponseStream());

                 string returnvalue = sr.ReadToEnd();

               //using Jobject to parse result
                
                 JObject mydata = JObject.Parse(returnvalue);
              
                JArray data = (JArray)mydata["data"];
             
               
            
                PosttofacePage(data);
            }



  I used   Json.net dll to Parse information from facebook,The dll can be found in http://json.codeplex.com/releases/view/89222
 Now its time to Post Data to Pages




          public void PosttofacePage(JArray obj)
            {

                for (int i = 0; i < obj.Count; i++)
                {
                    string name = (string)obj[i]["name"];
                    string Accesstoken = (string)obj[i]["access_token"];
                    string category = (string)obj[i]["category"];
                    string id = (string)obj[i]["id"];

                    string Message = "Test message";

                    if (string.IsNullOrEmpty(Message)) return;
                   
                    // Append the user's access token to the URL
                  string  path=String.Format("https://graph.facebook.com/{0}",id);
                    
                   var url = path+"/feed?" +
                       AppendKeyvalue("access_token",AccessToken);

                    // The POST body is just a collection of key=value pairs, the same way a URL GET string might be formatted

                    var parameters = ""

                        + AppendKeyvalue("name", "name")

                        + AppendKeyvalue("caption", "a test caption")

                        + AppendKeyvalue("description", "test description ")

                        + AppendKeyvalue("message", Message);

                    // Mark this request as a POST, and write the parameters to the method body (as opposed to the query string for a GET)

                    var webRequest = WebRequest.Create(url);

                    webRequest.ContentType = "application/x-www-form-urlencoded";

                    webRequest.Method = "POST";

                    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameters);

                    webRequest.ContentLength = bytes.Length;

                    System.IO.Stream os = webRequest.GetRequestStream();

                    os.Write(bytes, 0, bytes.Length);

                    os.Close();

                    // Send the request to Facebook, and query the result to get the confirmation code

                    try
                    {

                        var webResponse = webRequest.GetResponse();

                        StreamReader sr = null;

                        try
                        {

                            sr = new StreamReader(webResponse.GetResponseStream());

                            string PostID = sr.ReadToEnd();

                        }

                        finally
                        {

                            if (sr != null) sr.Close();

                        }

                    }
                    catch (WebException ex)
                    {

                        // To help with debugging, we grab the exception stream to get full error details

                        StreamReader errorStream = null;

                        try
                        {

                            errorStream = new StreamReader(ex.Response.GetResponseStream());

                            this.ErrorMessage = errorStream.ReadToEnd();

                        }
                        finally
                        {

                            if (errorStream != null) errorStream.Close();

                        }

                    }

                }
            }
 



  I Used AppendKeyvalue Mehod to Append Key value Pairs

  public static string AppendKeyvalue(string key, string value)
        {
            return string.Format("{0}={1}&", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value));
        }


 The above code Returns post id if posted successfully.
 Note: Access tokens are different For Different users
 That’s it We posted a new post on users page
 Happy coding






Thursday, 5 January 2012

How to fire and Forget a method in c#


iam not using begin invoke method for fear of potential leaks
first lets create class called AsyncHelper As Follows:
public class AsyncHelper
{


   
        class TargetInfo
        {
            internal TargetInfo(Delegate d, object[] args)
            {
                Target = d;
                Args = args;
            }

            internal readonly Delegate Target;
            internal readonly object[] Args;
        }

        private static WaitCallback dynamicInvokeShim = new WaitCallback(DynamicInvokeShim);

        public static void FireAndForget(Delegate d, params object[] args)
        {
            ThreadPool.QueueUserWorkItem(dynamicInvokeShim, new TargetInfo(d, args));
        }

        static void DynamicInvokeShim(object o)
        {
            try
            {
                TargetInfo ti = (TargetInfo)o;
                ti.Target.DynamicInvoke(ti.Args);
            }
            catch (Exception ex)
            {
                // Only use Trace as is Thread safe
                System.Diagnostics.Trace.WriteLine(ex.ToString());
            }
        }
    }




next Create a webpage  and Write to delegate to fire  a method and code will be as follows:

//Delegate Declartion

 delegate  int AddDelegate( int a,int b);
    protected void Page_Load(object sender, EventArgs e)
    {
//Invoking delegate and firing it
        AddDelegate d = new  AddDelegate(add);
        AsyncHelper.FireAndForget(d, 2, 3);


    }
// Method body
 public  int add(int a,int b)
 {
     
     return a + b;
 }

}

Thursday, 29 December 2011

How to Tweet on user Profile from asp.net website


Before we start  add Your application  to  twitter and get consumer ids

First Download Twitterizer from http://www.twitterizer.net/
and add that dlls to Your Project

Now place Two buttons  say authorization and Tweet buttons  and  text box say tweet text on web form
 Now in Authorization Button click event use this method
  protected void btnauthorize_Click(object sender, EventArgs e)
        {
           


            var consumerKey = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerKey"];
            var consumerSecret = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerSecretKey"];
            string callbackadress = "http://" + HttpContext.Current.Request.Url.Host + ":" + HttpContext.Current.Request.Url.Port + HttpContext.Current.Request.Url.PathAndQuery;

            //If User is not valid user
            if (Request.QueryString["oauth_token"] == null)
            {
                //Step 1: Get Request Token
                OAuthTokenResponse RequestToken = OAuthUtility.GetRequestToken(consumerKey, consumerSecret, callbackadress);

                //Step 2: Redirect User to Requested Token
                Response.Redirect("http://twitter.com/oauth/authorize?oauth_token=" + RequestToken.Token);
            }
        
        }
After authenticating that user
 we will be redirected To our url and place this code on page load vent to read user information


 protected void Page_Load(object sender, EventArgs e)
        {
          
            if (!string.IsNullOrEmpty(Request["oauth_verifier"]) && !Page.IsPostBack)
            {
                Readuserinformation();
            }
        }
        public void Readuserinformation()
        {
         
            var consumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"];
            var consumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecretKey"];
            string Oauth_Token = Request.QueryString["oauth_token"].ToString();
            var accessToken = OAuthUtility.GetAccessToken(consumerKey,
                                                  consumerSecret,
                                                  Oauth_Token, "");
          //Save this tokens For Tweeting

            string Token: = accessToken.Token;
            string TokenSecrt= accessToken.TokenSecret;
            string userid= accessToken.UserId;

        }
Now in tweetbutton click event call this method


  protected void btnTweet_Click(object sender, EventArgs e)
        {
         
            try
            {

                var consumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"];
                var consumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecretKey"];

                OAuthTokens accessToken = new OAuthTokens();
//Use the access token we got  after Reading user information
                accessToken.AccessToken = "xxxxxxx";
                accessToken.AccessTokenSecret = "xxxxxx";
                accessToken.ConsumerKey = consumerKey;
                accessToken.ConsumerSecret = consumerSecret;

                 

                Twitterizer.TwitterStatus.Update(accessToken, tbxTweet.Text);
            }
            catch (Exception ex)
            {


            }


        }
Happy coding

Monday, 26 December 2011

How to find nodes on tree view and expand them


Place searchtextbox,Button on webform which contains Treeview



In the search button click event call this method


 private void FindInTreeView(TreeNodeCollection tncoll, string strNode)
       {
         foreach (TreeNode tnode in tncoll)
    {
        if (tnode.Text.ToLower() == strNode.ToLower())
        {
            tnode.Selected = true;
         
                tnode.Expand();
                tnode.ExpandAll();
                if (tnode.Selected == true)
                {
                    searchtextbox.Text = null;
                }
          
           
         
        }
        else
        {
            tnode.Selected = false;
          
          
        }
        FindInTreeView(tnode.ChildNodes,strNode);
    }