Wednesday, May 30, 2012

mshtml / interface / COM Generic Casting example

ever tried something like this:
PrintAllElements<HTMLAnchorElement>();
and got all the elements where u have:

public static bool IsTypeOf<T>(object o)
{   return (o is T);   }

private void PrintAllElements<T>()
{
       HTMLDocument doc = webBrowser1.Document.DomDocument as HTMLDocument;
       foreach (IHTMLElement elem in doc.all)
       {
             if (IsTypeOf<T>(elem))
             {    //do stuff  }
       }
}

i mean IsTypeOf always true?
thats cuz all the HTML classes inherit the nice IHTMLElement so any IHTMLElement is T where T is HTMLxxxxxElement(Class).
but the solution is so very simple - send the interface as T like IHTMLAnchorElement so this works great with the same code:
PrintAllElements<IHTMLAnchorElement>();


this OC goes to all interfaces based classes like most of the COM object we have in C#

Tuesday, May 29, 2012

How To Test JQUERY AJAX call example by RNAN


$("#UpdateKM").click(function (e)
{
    var upkm = document.getElementById("newKmtxt").value;
    alert('myurl');
    $.ajax(
    {
        url: 'myurl',
        type: 'GET',
        dataType: 'json'
    }).done(function (result)
    {
        alert("done");  //or 1
    }).fail(function (xhr, status,errorThrown)
    {
        alert(errorThrown);   //or 2
    }).
    always(function (jqXHR, complete_textStatus)
    {
        alert('3');
    })
});
THANK U RNAN!!

Thursday, May 24, 2012

C# LIST.FOREACH +lambda example

never found a really simple example, see this:
List<string> parts = new List<string>();
parts.ForEach(delegate (string p) {
     Console.WriteLine(p);    });
since in lambda () is delegate() so
List<DateTime> dates = new List<DateTime>(); // just to show that T doesnt matter
parts.ForEach((DateTime d) =>
{
      Console.WriteLine(d);
});
PLUS u can do the remarkable list.Remove(d)! unlike foreach

C# WORD, and replace text, plus hebrew trick examlpe

the WordHandler class is the hard work of one of our ex-engineers.
pls remember that the number of parameters passed changes with the office versions
also u need to put the right Microsoft.Office.Interop.Word version, and its not according the office (word 14 is for office 10)
the trick is mine - the text backworded so a added in the word template val2 after val and it did the trick
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Word = Microsoft.Office.Interop.Word;
namespace WordFactory
{
     class Program
     {
        
static Word.Application oWord;
         static Word.Document oWordDoc;
         static void Main(string[] args)
         {
              WordHandler wh = new WordHandler();
              string pathA = @"F:\****.dot";
              string path = @"F:\****.dot";
              wh.CreateWord(path, out oWord, out oWordDoc);
              //the TRUTH == 201123USD01
              string acc = "201123USD01";
              string acc1 = " USD01 ";
              string acc2 = " ";
              // 01USD201123 --> USD20112301
              // 201123USD01 --> USD01201123
              //yes i put #VAL2# replace it with " " and its ok!
              ReplaceText("#VAL#", acc);
              ReplaceText("#VAL2#", " ");
              oWordDoc.Activate();
        }
        static private void ReplaceText(String old, String newWord)
        {
                object o = oWordDoc.Content.Start;
                object o2 = oWordDoc.Content.End - 1;
                Word.Range r = oWordDoc.Range(ref o, ref o2);
                Object missing = System.Reflection.Missing.Value;
                object replaceAll = Word.WdReplace.wdReplaceAll;
                r.Find.Text = old;
                r.Find.Replacement.Text = newWord;
                r.Find.Execute(
ref missing, ref missing, ref missing,   // number of params depends on office version
                        ref missing, ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing, ref replaceAll,
                        ref missing, ref missing, ref missing, ref missing);
         }
    }
   
   
    public class WordHandler
    {
             private Object oMissing = System.Reflection.Missing.Value;
             //OBJECTS OF FALSE AND TRUE
             private Object oTrue = true;
             private Object oFalse = false;
             public void KillApp()
            {
                   System.Diagnostics.
Process[] p = System.Diagnostics.Process.GetProcessesByName("WINWORD");
                   for (int i = 0; i < p.Length; i++)
                   {
                         try
                         {
                             p[i].Kill();
                         }
                         catch (Exception ex)
                         {
                                 if (ex.Message.ToLower().Contains("access is denied"))
                                         continue;
                          }
                    }
             }
       

             public void Print(ref Word.Document oWordDoc)
             {
                        object copies = "1";
                        object pages = "";
                        object range = Word.WdPrintOutRange.wdPrintAllDocument;
                        object items = Word.WdPrintOutItem.wdPrintDocumentContent;
                        object pageType = Word.WdPrintOutPages.wdPrintAllPages;
                        object oTrue = true;
                        object oFalse = false;
                        Object missing = System.Reflection.Missing.Value;
                        oWordDoc.PrintOut(ref oTrue, ref oFalse, ref range, ref missing, ref missing, ref missing,
                                     ref items, ref copies, ref pages, ref pageType, ref oFalse, ref oTrue,
                                     ref missing, ref oFalse, ref missing, ref missing, ref missing, ref missing);
              }
        

             public void CreateWord(String filename, out Word.Application oWord, out Word.Document oWordDoc)
             {
                   KillApp();
                   //CREATING OBJECTS OF WORD AND DOCUMENT
                  oWord = new Word.Application();
                  oWord.Visible = true;
                  oWordDoc = new Word.Document();
                  oWord.Visible = true;
                  //MAKING THE APPLICATION VISIBLE
                  // oWord.Visible = true;
                  //ADDING A NEW DOCUMENT TO THE APPLICATION
                  // oworddoc = oword.documents.add(ref omissing, ref omissing, ref omissing, ref omissing);
                  object isVisible = true;
                  Object oSaveAsFile = (Object)filename;
                  oWordDoc = oWord.Documents.Open(ref oSaveAsFile, ref oMissing, ref oMissing, ref oMissing,
                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                         ref oMissing, ref oMissing, ref isVisible, ref oMissing, ref oMissing
                        , ref oMissing, ref oMissing);
            }
       

            public void SaveFile(String fileName, ref Word.Application oWord,
                                                  ref Word.Document oWordDoc, Boolean delete)
            {
                     Object oSaveAsFile = (Object)fileName;
                     if (delete)
                     {
                             if (System.IO.File.Exists(fileName))
                                    System.IO.File.Delete(fileName);
                     }
           
          else
                             oSaveAsFile = (Object)(fileName + DateTime.Now.Second.ToString());
                     oWordDoc.SaveAs(ref oSaveAsFile, ref oMissing, ref oMissing, ref oMissing,
                                     ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                     ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                     ref oMissing, ref oMissing);
           }
       

            public void CreateWordBasedOnTemplate(String filename, String basedOn,
                                           out Word.Application oWord, out Word.Document oWordDoc)
            {
           
          //CREATING OBJECTS OF WORD AND DOCUMENT
                     oWord = new Word.Application();
                     oWordDoc = new Word.Document();
                     //MAKING THE APPLICATION VISIBLE
                     // oWord.Visible = true;
                     //ADDING A NEW DOCUMENT TO THE APPLICATION
                     //oWordDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                     Object oFilePath = basedOn;
                     oWordDoc = oWord.Documents.Add(ref oFilePath, ref oMissing, ref oMissing, ref oTrue);
                     //oWordDoc.Bookmarks.get_Item(ref oBookMark).Range.InsertFile(
                     //       oFilePath, ref oMissing, ref oFalse, ref oFalse, ref oFalse);
                     Object oSaveAsFile = (Object)filename;
                   oWordDoc.SaveAs(ref oSaveAsFile, ref oMissing, ref oMissing, ref oMissing,
                             ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                             ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                             ref oMissing, ref oMissing);
            }
       

            public void FindAndReplace(Word.Application oWord, object findText, object replaceText)
           {
                 object matchCase = true;
                 object matchWholeWord = true;
                 object matchWildCards = false;
                 object matchSoundsLine = false;
                 object nmatchAllWordForms = false;
                 object forward = true;
                 object format = false;
                 object matchKashida = false;
                 object matchDiacritics = false;
                 object matchAlefHamza = false;
                 object matchControl = false;
                 object read_only = false;
                 object visible = true;
                 object replace = 2;
                 object wrap = 1;
                 oWord.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord,
                            ref matchWildCards, ref matchSoundsLine,
                            ref nmatchAllWordForms, ref forward, ref wrap, ref format, ref replaceText, ref replace,
                            ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
           }
     }
}

Change Proxy C# example

ye i know there r millions exapmle but i wanna point out 2 thing:       
string todaysProxy = "192.168.0.254:3128";
RegistryKey registry = Registry.CurrentUser.OpenSubKey
             ("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", "00000001", RegistryValueKind.DWord);
registry.SetValue("ProxyEnable", 1);
registry.SetValue("ProxyServer", todaysProxy);
registry.SetValue("ProxyOverride", "192.168.0.*;127.0.0.*;localhost");

1 - ProxyEnable - either int 1 or define kind, unlike the batch
2 - O.C. IT WONT TAKE IMMIDIATE AFFECT but only on the new sessions, unless:
http://stackoverflow.com/questions/2020363/how-to-change-global-windows-proxy-using-c-sharp-net-with-immediate-effect

C# Read Excel File - EOProlbems!

sooo simple and genius!!
explanations:
http://code.google.com/p/linqtoexcel/
http://code.google.com/p/linqtoexcel/wiki/UsingLinqToExcel
download:http://code.google.com/p/linqtoexcel/downloads/list
most basic print:
var excel = new ExcelQueryFactory(@"F:\\MEMBER Book.xlsx");
var all = from c in excel.Worksheet()
               select c;
foreach (var row in all)
{
     
foreach (var cell in row)
            Console.Write(cell.Value + "   ");
      Console.WriteLine();
}


Update:
another thing i've been told of by Yon1973
http://www.rssbus.com/kb/help/RXR1-A/pg_usage.rst
use it with ADO

Update 2:
another reader for xls and other
http://npoi.codeplex.com/

Wednesday, May 23, 2012

MySQL IndexOf and Substring example

example to select the name only
SELECT INSTR('ariel@lti', '@');
SELECT SUBSTRING('MySQL Substring',7,3);

SELECT Name, Email ,
   INSTR(Email, '@') as indx,
   SUBSTRING(Email, 1INSTR(Email, '@')-1) as wow ,
   SUBSTRING(Email, 1, 9) AS nooo
FROM supplier_contact WHERE name='No Info';

 
example to select the domain only
SELECT SUBSTRING(Email, INSTR(Email, '@')+1, LENGTH(Email)) AS domain, Email
FROM supplier_contact