Monday, April 30, 2012

IIS, DLL and Exhange

Sunday, April 29, 2012

Catch Enter on ASP Form example

1st thing u must know - u cant do it directly like any other controls.OnTextChange
therefor the good lord gave us JS!
put this script on:
<script language="javascript" type="text/javascript">   
   document.onkeypress = function() {      
      if (window.event.keyCode==13){
          alert(window.event.keyCode); //to see that it works      

This on the aspx page :
<input id="Hidden1" type="hidden" runat="server"/>

and on the cs page:
protected void Page_Load(object sender, EventArgs e)
    if (Hidden1.Value == "true")
         TextBox1.Text = "We Got an Enter to the Server Side";
         TextBox1.Text = "just a page load, no enter";        
//put a TextBox with width 300, run the page and press enter :)

Wednesday, April 25, 2012

Access: Call a Func from another Form with example

the main points are:
1 - make the func public (daa but we forget) and "As Variant"
2 - actualy find the damn form and how to call the func
when u have that u have it (double daa)
and for the example
call a func in a subform from the main form
the func:
Public Function Call_payment_date_AfterUpdate() As Variant
End Function
from the main form (in a func o/c)
Forms!ei_main_form![ei_purchase subsubform].Form.Call_payment_date_AfterUpdate

from a stand alone form call a func in another form
the func
Public Function Call_Refresh_From_ei_main() As Variant    Me.Refresh
End Function

the call

תקשורת על גבי רשת האינטרנט מאת ALEXSUH

כל התודות לאלכס מפורום תפוז שהשקיע בנו כ"כ, הכל מועתק ללא שינוי

מה שאתה מדבר עליו נקרא פרוטוקול SOAP לתקשורת על גבי רשת האינטרנט.
זה פרוטוקול מקובל בד"כ אם אתה שולט הן בצד השרת וצד הלקוח .
סיומת ASMX מקובלת במימוש הפרוטוקול על גבי שרתי MISCROSOFT מסוג ASP.NET אך הפוטוקול אינו ייחודי ל MIcrosoft וניתן לשתמש בכל סיומת כל עוד עומדים בתקנים של הפרוטוקול.
בעולם האמיתי לא תמיד ניתן לקבל שירות נוח של קליק וגמרנו ומדי פעם צריך לבצע קצת עבודה ע"מ לקבל את הנתונים.
במקרה הנ"ל אין מדובר בשרות מסוג SOAP אלא בקובץ XML רגיל אשר מתעדכן אחת לכמה זמן (לדעתי פעמיים שלוש ביום) וניתן להורדה ישירה תוך שימוש בפרוטוקול HTTP רגיל.

קצת רקע
עוד מידע על לפרוטוקול SOAP

פרוטוקול HTTP עליו פרוטוקול SOAP מבוסס

פרוטוקולים נוספים המבוססים על HTTP
XML-RPC (המיושן אך עדיין נפוץ בפינות נשכחות של האינטרנט)

לגבי השיטה שהצעתי - עליך קודם כל להוריד את הקובץ

לקרוא את הקובץ על מנת להגיע לנתונים

יתכן שתצתרך להעזר ב DOM , XPATH או XQUERY לשם כך
(ממליץ ללככת על XPATH)

ולבסוף להציב את הנתונים בממשק המשתמש שבנית (בין אם זה וובי או לא)


Sunday, April 22, 2012

Ajax Image Asp example

1st we need a source to return a requested img, i'll use an ASP page like this (ASPX part doesnt matter, u may not touch it), lets call it ReturnPic.aspx
protected void Page_Load(object sender, EventArgs e)
    System.Drawing.Image img = System.Drawing.Image.FromFile(         Request.QueryString["file"].ToString());
    //u have to use the system.drawing or ull get the we.ui.image    string ext = Path.GetExtension(Request.QueryString["file"].ToString());
    if (ext == "jpg")
       ext = "jpeg";
   *MemoryStream ms = new MemoryStream();
    img.Save(ms, System.Drawing.Imaging.
    byte[] content = ms.ToArray();
    Response.ContentType = "image/" + ext;
u can always use ImageConverter

now here is my default page, i used 2 method to return the pic by ajax, one with UpdatePanel and the other with WebMethod both explained in my post:
o/c the ddl was filled in the pageLoad
<script type="text/javascript">
  function ChangeSource(times){
     var e = document.getElementById("ddlImg");
     var num = 0;
     num = num + e.options[e.selectedIndex].value;
     PageMethods.ChangeSource(num, ChangeSourceComplete);
function ChangeSourceComplete(result){
   var div = document.getElementById("img2");
   div.src = result;
}            </script>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnablePageMethods="true" >   --->>> if ur planing use the webmethod
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <asp:Button runat="server" Text="Button" ID="btnChangeImg"
        onclick="btnChangeImg_Click" /> <br />
    <img id="img1" alt="" src="" runat="server"/>
<asp:DropDownList ID="ddlImg" runat="server">
</asp:DropDownList><br />
<input id="Button1" type="button" value="button"
     onclick="ChangeSource();" /><br />
<img id="img2" alt="" src="" />

for the UpdatePanel Btn:
protected void btnChangeImg_Click(object sender, EventArgs e)
     Random rnd = new Random();
     int r = rnd.Next(3);
     string file = "";
     switch (r)
          case 0: file = @"H:\My Pictures\white-light1.jpg"; break;
          case 1: file = @"H:\My " +
                    Pictures\p4788853bb1286d6947587e8ec3b6090f2181898.gif"; break;
          case 2: file = @"H:\My Pictures\have-a-nice-day.jpg"; break;
          default: break;
    img1.Src = "ReturnPic.aspx?file=" + file;

for the lower part and its JS code u need
public static string ChangeSource(int num)
    string file = "";
    switch (num)
          case 0: file = @"H:\My Pictures\white-light1.jpg"; break;
          case 1: file = @"H:\My " +
                     Pictures\p4788853bb1286d6947587e8ec3b6090f2181898.gif"; break;
          case 2: file = @"H:\My Pictures\have-a-nice-day.jpg"; break;
          default: break;
    }    return "ReturnPic.aspx?file=" + file;

just try it - its cool

Thursday, April 19, 2012

Linq Vs Mysql

the answer - mysql (and i guess any sql kind) is about 500-1000 times faster
BUT, yes we have a HUGE but - this is only for the query time the SQL query himself from the DB.
then we have transportation - there, the bigger the data requested is the more u might be better using Linq, AND we have a BUT here too - Linq depends on ur computer resources so...

anyway on my job's machine i did a query from a table with 300K+ rows.
when the answer was less than 100 rows the mysql was that fast.
when i tried something with 60k+ rows and another with 250K rows the Linq became 60%+ faster.
*!this does not include the initial query of all the 300K lines

Soooo...   for me it means that if i am gonna query something alot it might be better a Linq or even 2 querys on something with 60K+ rows

on 4K they r the same
20K Linq is faster by about 20%+
again my machine my router speed...

my conclusion:
*Linq is better when u query at least 3-5 times and more AND were talking about 10K+ rows a query
SQL is ALWAYS better if u query once (DAAA...)
*SQL is better when u query more than once AND were talking less about 5K+ rows a query
*these numbers also depend on transportation and W/O initial query

Wednesday, April 18, 2012

DataSource a Linq(ed) DataTable example

if u ever tried to query with Linq a datatable and then assign it to a DataGridView (and other stuff i guess) then u might have noticed that the grid shows the properties of the DataRow(s).
And if you tried to select the ItemArray, again a mess.
Sooo... its so simple i laugh at myself but i must:

var query =
     from data in tblAllData.AsEnumerable()
     where data.Field<DateTime>("Start").Month == (int)cmbMonths.SelectedValue
     select data;
if (query.Count() > 0)                
    dgvMain.DataSource = query.CopyToDataTable();


Winforms ComboBox Text & Value example

the really simple way, and goes for the rest of the winform controls
you could also put a list of any class and choose 2 properties

DataTable tblMonths = new DataTable();
tblMonths.Columns.Add(new DataColumn("Name", typeof(string)));
tblMonths.Columns.Add(new DataColumn("Value", typeof(int)));
for (int i = 1; i <= 12; i++)
    string month = DateTimeFormatInfo.CurrentInfo.GetMonthName(i);
    new object[] { month, i });
cmbMonths.DataSource = tblMonths;
cmbMonths.ValueMember = "Value";

cmbMonths.DisplayMember = "Name";
cmbMonths.SelectedValue =

Tuesday, April 17, 2012

mysql Count the Distinct example

I want select like this:
ari     3
dani  1
SELECT   my_column,  
COUNT(*) AS num
FROM my_table
GROUP BY  my_column
thanks stack overflow

WinForms Bypass Cross Thread Update Error example

we can do 2 things
the 1st, not everybody loves it (and i guess that in large slns  u should avoid it) is the
CheckForIllegalCrossThreadCalls  prop:.

public Form1()
    Form1.CheckForIllegalCrossThreadCalls = false;
 private void button1_Click(object sender, EventArgs e)
     Thread t = new Thread(new ThreadStart(target));
 private void target()
     this.Text = "ddddd";

the other way is to use a delegate:

delegate void SetTextCallback(string text);
private void SetText(string text)
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
   if (this.textBox1.InvokeRequired)
      SetTextCallback d = new SetTextCallback(SetText);
      this.Invoke(d, new object[] { text });
       this.textBox1.Text = textBox1.Text + text;
p.s. - thanks to rabi dot net and stack overflow

Sunday, April 15, 2012

Ease of WebRequest example

this is and example of a generic method to execute POST WebRequests, and in this case login into a site, don't worry, the values are fake.

the 1st part is a secondary example, how to call MakeWebRequest method itself, which is the main thing in this post.

System.Collections.Specialized; - ns for NameValueCollection
NameValueCollection parameters = new NameValueCollection();

parameters.Add("textBox1", "422");
parameters.Add("textBox2", "gensearch");
parameters.Add("textBoxUserName", "UserName");
parameters.Add("textBoxPassword", "mode matchallpartial");
string strRes = "";
string url = "\jsp\php\ect.";
CookieContainer cookie = new CookieContainer();

MakeWebRequest(url, "POST", ref cookie, parameters, ref strRes);

//and strRes is our response, either html or csv or whatever the resposne is
//if you dont send any params then parameters is null and mehtod is "GET"
//if you need a page that require a pre login just resend the cookie

System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
wb.DocumentText = strRes;

HTMLDocument doc = (HTMLDocument )wb.Document.DomDocument

public bool MakeWebRequest(String url, String method,
ref CookieContainer cookies, NameValueCollection parameters,
ref String strResponse)
{  HttpWebRequest request;
  HttpWebResponse response;
   request = (   HttpWebRequest)WebRequest.Create(url);
  request.AllowAutoRedirect = true;
  request.CookieContainer = cookies;
  request.Method = method;  if ((parameters != null) && (parameters.Count > 0))
  {      bool first = true;
      StringBuilder sbData = new StringBuilder();
      foreach (String key in parameters.AllKeys)
        if (first)
          first = false;
    if ("POST" == request.Method)
      request.ContentType =          "application/x-www-form-urlencoded";
      request.ContentLength = sbData.Length;
   }   StreamWriter sw = new StreamWriter(request.GetRequestStream());
response = (
cookies = request.CookieContainer;
StreamReader sr = new StreamReader(response.GetResponseStream());
strResponse = sr.ReadToEnd();

return true;
//end make web req

Paralel Events example

So you wanna have 2 events running at the same time (parallel)?
nope - they will run as a stack, we need , threads!
so typically I would recommend using the TPL library but sometimes its not exactly what you need, and sometimes you work with .Net 3.5.

If we just start new thread in WinForms we also get cross trread exception... - this is solved with delegates!

Here is my code for 2 textboxes with doubleClick event to write to a 3rd textbox, 1st textbox by an event, the other textbox by a thread.

note that the event are still in a stack although they get a different class.
the threads should work without a class but this is a pattern for "heavier" work:

public partial class Eventer : Form
     int id = 10;
     public Eventer()
    private void txtEnter_DoubleClick(object sender, EventArgs e)
         cWriter cw = new cWriter(id++);
         cw.SendBack += new cWriter.BackToTextBox(cw_SendBack);

      private void txtStartThread_DoubleClick(object sender, EventArgs e)
           object oID = id++;
           Thread t = new Thread(new ParameterizedThreadStart(StartSingleThread));

      void StartSingleThread(object oID)
            int id = (int)oID;
            cWriter cw = new cWriter(id);
            cw.SendBack += new cWriter.BackToTextBox(cw_SendBack);

     void cw_SendBack(string str)
            if (txtBigBox.InvokeRequired)
                 SetTextCallback d = new SetTextCallback(cw_SendBack);
                 this.Invoke(d, new object[] { str });

     delegate void SetTextCallback(string text);
}//end class form

public class cWriter
       public delegate void Writer(int id);
       public event Writer StartWrite;
       public delegate void BackToTextBox(string str);
       public event BackToTextBox SendBack;
       int id;
       public cWriter(int id)
   = id;

       public void StartWriting()
            StartWrite += new Writer(cWriter_StartWrite);

       void cWriter_StartWrite(int id)
             for (int i = 0; i < 10; i++)
                     SendBack(id.ToString() + " " +
                     DateTime.Now.ToLongTimeString() + "\r\n");
}//end cwriter

Tuesday, April 3, 2012

Ajax - the 3 simple ways example

the most easy way to do ajax, if you're developing with .Net, is to use the AjaxUpdatePanel. tp use it you must add a script manager to your page, preferred in you master page if you have one, and from there on all your standard logic and fields and whatever inside the Content Template

<asp:ScriptManager ID="ScriptManager1" runat="server" > </asp:ScriptManager>
<asp:UpdatePanel ID="uppContact" runat="server" UpdateMode="Conditional">
      <!-- html tags -->
      <%-- server tags --%>
most developers don't like the UpdatePanel and for good reasons:
1 - for it to trigger you need a server control that will trigger a post back
2 - it actually do a full postback, with a full page life cycle, and a full response, only in the client if "fakes" it to feel as only whatever in the panel has changed, meaning its really heavy, and kinda lose the point of ajax, its more useful for big stuff like paging or big forms.
another option given by the .Net framework is the PageMethods, where if you develop a .Net page you can give some static methods a WebMethod attribute (System.Web.Services) and call them from the client. For that you must enable the page methods within the script manager

<asp:ScriptManager ID="ScriptManager2" runat="server" EnablePageMethods="true"> </asp:ScriptManager>

an example for a WebMethods in the server code:

public static string GetTime(int modifier)
      return DateTime.Now.AddDays(modifier);

and in order to call it via javascript you need 2 methods, one to call it and another for the callback:

function GetTime(value){
    PageMethods.UpdateExstension(c, conId, OnUpdateComplete);

function OnUpdateComplete(result){

the last option, and the most common one, is the original one, using jQuery

using jQuery in your page you must use a jQuery lib of any version, for example

<script src="jquery-1.9.1.min.js" ></script>

you are most welcome to use their CDN's like this

<script src="" ></script>

here we can choose what to call, a WebMethod, some generic handler, or any api available, lets start by demonstrating how to call a WebMethod

<script type="text/javascript">
$(document).ready(function () {
    // Add the page method call as an onclick handler for the div.
    $("#MyButton").click(function () {
            type: "POST",
            url: "Default.aspx/GetDate",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
               // Replace the div's content with the page method's return.
               $("#Result").text(msg.d); //DO NOT FORGET .d

in case you don't want to use any WebMethod, or maybe you just can't, then its really easy to create a handler for yourself. I have 2 posts, one with some explanations and the other with an example

from there the ajax call gets as easy as this

url: "Handler1.ashx",
  success: function (data) {